存储过程和存储函数
Posted bibiafa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了存储过程和存储函数相关的知识,希望对你有一定的参考价值。
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;
以上是关于存储过程和存储函数的主要内容,如果未能解决你的问题,请参考以下文章