您的代码块没有定义声明变量的范围。如果在一个过程中,它们必须在BEGIN
和之间END
。没有它们,该语句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
或者遵循为存储过程定义的语法来使用范围变量。
示例 1:使用会话变量:
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)
请注意,您可以在过程中设置/定义会话变量,但不能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>
另请参阅变量声明和范围。