1. 程式人生 > >存儲過程和存儲函數

存儲過程和存儲函數

limit select call 作用範圍 varchar color 錯誤 into cal

grade表:

select * from grade;
+----+------+--------+------+-------+-------+
| id | name | sexy   | age  | score | class |
+----+------+--------+------+-------+-------+
|  1 | a    | male   |   15 |    90 | A(1)  |
|  2 | b    | male   |   13 |    97 | A(1)  |
|  3 | c    | female |   15 |    79 | A(2
) | | 4 | a | female | 13 | 100 | B(1) | | 5 | d | male | 16 | 89 | B(2) | | 6 | e | male | 16 | 97 | B(2) | | 7 | f | female | 15 | 93 | B(3) | | 8 | g | female | 13 | 88 | C(1) | | 9 | h | male | 14 | 91 | C(2) | +----+------+--------+------+-------+-------+

創建存儲過程p_grade

delimiter &&
create procedure p_grade(in g_id int,out g_name varchar(20))
begin
declare g_score varchar(20);
select score into g_score from grade where id = g_id;
select name into g_name from grade where id = g_id;
select g_score;
end
&&
delimiter ;
call p_grade(1,@n
); +---------+ | g_score | +---------+ | 90 | +---------+
select @n;
+------+
| @n   |
+------+
| a    |
+------+

1.參數g_name的作用範圍是begin...end之間

2.declare聲明的變量作用範圍是begin...end之間

3.declare必須在所有set前面,即使是變量g_name,也必須在所有declare之後賦值。

4.declare可以聲明多個變量,但是多個變量的類型必須一致。

  正確語法:declare a,b,c int default 10;

  錯誤語法: declare a int,b int,c int;

5.sql語句中為了給g_score和g_name賦值,使用了兩條select語句。簡潔寫法如下

  select score,name into g_score,g_name from grade where id = g_id;

  

存儲過程和存儲函數