The scope of a local variable is the 局部变量的作用域是在其中声明的BEGIN ... END
block within which it is declared. BEGIN ... END
块。The variable can be referred to in blocks nested within the declaring block, except those blocks that declare a variable with the same name.可以在嵌套在声明块中的块中引用变量,但声明具有相同名称的变量的块除外。
Because local variables are in scope only during stored program execution, references to them are not permitted in prepared statements created within a stored program. 由于局部变量仅在存储程序执行期间在作用域中,因此在存储程序中创建的准备语句中不允许引用它们。Prepared statement scope is the current session, not the stored program, so the statement could be executed after the program ends, at which point the variables would no longer be in scope. Prepared语句作用域是当前会话,而不是存储程序,因此语句可以在程序结束后执行,此时变量将不再在作用域中。For example, 例如,SELECT ... INTO
cannot be used as a prepared statement. local_var
SELECT ... INTO
不能用作准备语句。local_var
This restriction also applies to stored procedure and function parameters. 此限制也适用于存储过程和函数参数。See Section 13.5.1, “PREPARE Statement”.请参阅第13.5.1节,“PREPARE语句”。
A local variable should not have the same name as a table column. 局部变量不应与表列同名。If an SQL statement, such as a 如果SQL语句,例如SELECT ... INTO
statement, contains a reference to a column and a declared local variable with the same name, MySQL currently interprets the reference as the name of a variable. SELECT ... INTO
语句,包含对列的引用和声明的同名局部变量,MySQL当前将引用解释为变量的名称。Consider the following procedure definition:考虑下面的过程定义:
CREATE PROCEDURE sp1 (x VARCHAR(5)) BEGIN DECLARE xname VARCHAR(5) DEFAULT 'bob'; DECLARE newname VARCHAR(5); DECLARE xid INT; SELECT xname, id INTO newname, xid FROM table1 WHERE xname = xname; SELECT newname; END;
MySQL interprets MySQL将xname
in the SELECT
statement as a reference to the xname
variable rather than the xname
column. SELECT
语句中的xname
解释为对xname
变量的引用,而不是对xname
列的引用。Consequently, when the procedure 因此,当调用过程sp1()
is called, the newname
variable returns the value 'bob'
regardless of the value of the table1.xname
column.sp1()
时,newname
变量返回值'bob'
,而不管table1.xname
列的值是多少。
Similarly, the cursor definition in the following procedure contains a 类似地,以下过程中的游标定义包含引用SELECT
statement that refers to xname
. xname
的SELECT
语句。MySQL interprets this as a reference to the variable of that name rather than a column reference.MySQL将其解释为对该名称的变量的引用,而不是列引用。
CREATE PROCEDURE sp2 (x VARCHAR(5)) BEGIN DECLARE xname VARCHAR(5) DEFAULT 'bob'; DECLARE newname VARCHAR(5); DECLARE xid INT; DECLARE done TINYINT DEFAULT 0; DECLARE cur1 CURSOR FOR SELECT xname, id FROM table1; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur1; read_loop: LOOP FETCH FROM cur1 INTO newname, xid; IF done THEN LEAVE read_loop; END IF; SELECT newname; END LOOP; CLOSE cur1; END;
See also Section 25.8, “Restrictions on Stored Programs”.另请参见第25.8节,“存储程序的限制”。