您好,欢迎访问一九零五行业门户网

MySQL5新语句declare的用法_MySQL

新sql语句,在复合语句中声明变量的指令是declare。
(1) example with two declare statements
两个declare语句的例子
create procedure p8 ()
begin
declare a int;
declare b int;
set a = 5;
set b = 5;
insert into t values (a);
select s1 * a from t where s1 >= b;
end; // /* i won't call this */在过程中定义的变量并不是真正的定义,你只是在begin/end块内定义了而已(译注:也就是形参)。注意这些变量和会话变量不一样,不能使用修饰符@你必须清楚的在begin/end块中声明变量和它们的类型。变量一旦声明,你就能在任何能使用会话变量、文字、列名的地方使用。
(2)example with no default clause and set statement
没有默认子句和设定语句的例子
create procedure p9 ()
begin
declare a int /* there is no default clause */;
declare b int /* there is no default clause */;
set a = 5; /* there is a set statement */
set b = 5; /* there is a set statement */
insert into t values (a);
select s1 * a from t where s1 >= b;
end; // /* i won't call this */
有很多初始化变量的方法。如果没有默认的子句,那么变量的初始值为null。你可以在任何时候使用set语句给变量赋值。
(3)example with default clause
含有default子句的例子
create procedure p10 ()
begin
declare a, b int default 5;
insert into t values (a);
select s1 * a from t where s1 >= b;
end; //
我们在这里做了一些改变,但是结果还是一样的。在这里使用了default子句来设定初始值,这就不需要把declare和set语句的实现分开了。 
  (4)example of call
    调用的例子
mysql> call p10() //
+--------+
| s1 * a |
+--------+
| 25 |
| 25 |
+--------+
2 rows in set (0.00 sec)
query ok, 0 rows affected (0.00 sec)
结果显示了过程能正常工作
(5) scope
作用域
create procedure p11 ()
begin
declare x1 char(5) default 'outer';
begin
declare x1 char(5) default 'inner';
select x1;
end;
select x1;
end; //
现在我们来讨论一下作用域的问题。例子中有嵌套的begin/end块,当然这是合法的。同时包含两个变量,名字都是x1,这样也是合法的。内部的变量在其作用域内享有更高的优先权。当执行到end语句时,内部变量消失,此时已经在其作用域外,变量不再可见了,因此在存储过程外再也不能找到这个声明了的变量,但是你可以通过out参数或者将其值指派 给会话变量来保存其值。
调用作用域例子的过程:
mysql> call p11()//
+-------+
| x1 |
+-------+
| inner |
+-------+
+-------+
| x1 |
+-------+
| outer |
+-------+
我们看到的结果时第一个select语句检索到最内层的变量,第二个检索到第二层的变量
其它类似信息

推荐信息