MySQL中创建存储过程示例

在这个示例中需要用到一张名为test_table的表,我们使用show create table test_table查看表的创建过程:

CREATE TABLE `test_table` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `brief` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

接下来我们演示以下创建名为test_procedure的表,
我们在创建存储过程之前要先判断存储过程是否存在,若存在,先删除之:

drop procedure if exists test_procedure;

然后创建存储过程:

create procedure test_procedure()
begin
	declare t_error integer default 0;
	declare continue handler for sqlexception set t_error=1;
	start transaction;
	delete from test_table;
	insert into test_table (id,name,age,brief) values 
			(1, 'zifeiy', 38, 'nothing to do'),
			(2, 'balala', 22, 'hello world');
	insert into test_table (id,name,age,brief) values 
			(3, 'hello', 11, 'hello'),
			(4, 'haha', 2, 'haha');
	if t_error = 1 then 
		rollback;
	else 
		commit;
	end if;
	select t_error;
end

然后调用1存储过程:

call test_procedure();

可以看到存储过程返回的结果:

t_error
0

然后通过SQL语句select * from test_table查看目标表中的数据如下:

id name age brief
1 zifeiy 38 nothing to do
2 balala 22 hello world
3 hello 11 hello
4 haha 2 haha
原文地址:https://www.cnblogs.com/zifeiy/p/9993430.html