• 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
  • 相关阅读:
    排序算法整理
    V-REP Plugin 开发
    YAML-CPP
    YAML
    V-REP Remote API
    V-REP Plugin
    结构化方法与面向对象方法的比较
    敏捷软件开发vs传统软件工程
    个人项目-地铁出行路线规划程序
    Week1个人作业
  • 原文地址:https://www.cnblogs.com/zifeiy/p/9993430.html
Copyright © 2020-2023  润新知