gpt4 book ai didi

MySQL语法错误

转载 作者:行者123 更新时间:2023-11-29 00:39:16 24 4
gpt4 key购买 nike

我无法在 MySQL 中运行简单的脚本。我已将脚本缩减为一行。

DELIMITER $$
DECLARE varLocalityName VARCHAR(50);
$$
DELIMITER ;

错误是:

ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE varLocalityName VARCHAR(50)' at line 1

$ mysql --version
mysql Ver 14.14 Distrib 5.1.63, for debian-linux-gnu (x86_64) using readline 6.2

最佳答案

您的代码块没有定义声明变量的范围。如果在过程中,它们必须在 BEGINEND 之间。没有它们,语句 DECLARE varLocalityName VARCHAR(50); 将成为要执行的无效语句。此语句等同于下面显示的语句:

mysql> select current_date();
+----------------+
| current_date() |
+----------------+
| 2012-10-22 |
+----------------+
1 row in set (0.00 sec)

mysql> declare varLocalityName varchar(50);
ERROR 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near 'declare varLocalityName varchar(50)' at line 1
mysql>

要么您应该声明不带关键字DECLARE 的 session 变量,要么遵循为存储过程定义的语法以使用作用域变量。

示例 1:使用 session 变量:

mysql> set @x = null;
Query OK, 0 rows affected (0.00 sec)
mysql> select @x;
+------+
| @x |
+------+
| NULL |
+------+
1 row in set (0.00 sec)

mysql> delimiter $$
mysql> select current_date() into @x;
-> $$
Query OK, 1 row affected (0.02 sec)

mysql> select @x;
-> $$
+------------+
| @x |
+------------+
| 2012-10-22 |
+------------+
1 row in set (0.00 sec)

请注意,您可以在过程中设置/定义 session 变量,但不能DECLARE

示例 2:使用过程范围变量:

mysql>
mysql> delimiter $$
mysql> create procedure some_x()
-> begin
-> declare varLocalityName varchar(50);
->
-> set @sessionDate = null;
-> select @sessionDate;
-> set @sessionDate = current_date();
-> select @sessionDate;
->
-> select varLocalityName;
-> end;
-> $$
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql>
mysql> call some_x();
+--------------+
| @sessionDate |
+--------------+
| NULL |
+--------------+
1 row in set (0.00 sec)

+--------------+
| @sessionDate |
+--------------+
| 2012-10-22 |
+--------------+
1 row in set (0.00 sec)

+-----------------+
| varLocalityName |
+-----------------+
| NULL |
+-----------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> select @sessionDate;
+--------------+
| @sessionDate |
+--------------+
| 2012-10-22 |
+--------------+
1 row in set (0.00 sec)

mysql> select varLocalityName;
ERROR 1054 (42S22): Unknown column 'varLocalityName' in 'field list'
mysql>

另请参阅 Variables declaration and scope .

关于MySQL语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13007687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com