一、小例子

(1)存储过程实现内容

按照给定的输入参数,插入相应的值,并将结果集赋予输出参数。

存储过程定义:

create procedure "SumVal"(in FilterVal int, out SumResult bigint)
begin
	#declare cur ref cursor;
	declare InsertSql text;
	
	set InsertSql = 'insert into czg values(?)';
	set @sqlstr = InsertSql;
	set @a = FilterVal;
	prepare stmt from @sqlstr;
	EXECUTE stmt using @a; 
	select count(*) into SumResult from czg where a = FilterVal;
	deallocate prepare stmt;
end; 

(2)测试步骤

生成czg表测试数据请查看之前的链接:《南大通用数据库-Gbase-8a-学习-01-存储过程及函数之IF、LOOP、LEAVE、SET》

gbase> select * from czg;
+------+
| a    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
10 rows in set (Elapsed: 00:00:00.00)

gbase> drop procedure if exists "SumVal";
Query OK, 0 rows affected (Elapsed: 00:00:00.00)

gbase> DELIMITER //
gbase> create procedure "SumVal"(in FilterVal int, out SumResult bigint)
    -> begin
    -> #declare cur ref cursor;
    -> declare InsertSql text;
    -> 
    -> set InsertSql = 'insert into czg values(?)';
    -> set @sqlstr = InsertSql;
    -> set @a = FilterVal;
    -> prepare stmt from @sqlstr;
    -> EXECUTE stmt using @a; 
    -> select count(*) into SumResult from czg where a = FilterVal;
    -> deallocate prepare stmt;
    -> end; //
Query OK, 0 rows affected (Elapsed: 00:00:00.01)

gbase> set @ParameterOut = 0;//
Query OK, 0 rows affected (Elapsed: 00:00:00.00)

gbase> call SumVal(99,@ParameterOut);//
Query OK, 0 rows affected (Elapsed: 00:00:00.05)

gbase> select @ParameterOut;//
+---------------+
| @ParameterOut |
+---------------+
|             1 |
+---------------+
1 row in set (Elapsed: 00:00:00.00)

gbase> select * from czg;//
+------+
| a    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
|   99 |
+------+
11 rows in set (Elapsed: 00:00:00.00)

二、涉及的语法

(1)PREPARE

语法格式:

PREPARE stmt_name FROM preparable_stmt

语法解释:
准备语句,这个步骤会对Sql进行语法语义解析,后续如果根据此语句句柄执行Sql,可以跳过语法语义解析阶段,加快了Sql执行效率。

(2)EXECUTE

语法格式:

EXECUTE stmt_name [USING @var_name [, @var_name] ...]

语法解释:
执行相应Sql语句,并可以在执行时将参数带入。

(3)DEALLOCATE

语法格式:

DEALLOCATE PREPARE stmt_name

语法解释:
释放语句句柄,和(1)PREPARE 一一对应,避免造成资源不释放。

(4)@变量

语法格式:

@变量

语法解释:
会话级的变量,和declare定义的变量作用域不同,declare定义的变量作用域在begin和end之间。

(5)into

语法格式:

selectinto 变量 from 表名 [where 条件];

语法解释:
将查询的结果赋予变量。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐