MySQL中创建存储过程示例

本文详细介绍了一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值