springboot 初始化sql脚本。mysql建立存储过程,判断列字段是否存在不存在就添加

499 阅读2分钟

学习记录

1、什么是存储过程???

存储过程简单来说(创建存储过程就相当于创建一个class或者function),就是为以后的使用而保存的一条或多条 MySQL 语句的[集合]可将其视为批处理文件。虽然他们的作用不仅限于批处理。相当于一个function讲一些操作或者判断放在function里面,到了需要的时候直接调用。存储过程支持传参返参,在存储过程调用其它的存储过程。简单来说就相当于方法调用发放。

🌰如下:

#drop: 删除 procedure: 存储过程 if exists myLee6:如果存储过程myLee6存储的话
drop procedure if exists myLee6;

#创建存储过程 可以定义参数 in:入参、out:出参 myLee6(in name varchar(20), out sex int)
create procedure myLee6()

#beginend 表示过程主体的开始和结束,相当于 Java 定义方法的一对大括号{}
begin

#判断是否有列name3如果,如果没有插入列name3
    IF(select 1 from information_schema.columns  where table_schema='white_jotter' and table_name='user_info' and column_name ='name3') THEN
        SELECT '已经有了'; // set sex = 2;
    ELSE
        alter table user_info add column name3 varchar(20) not null;
#记住需要添加流程控制语句的结束符
    END IF;
    
# 存储过程结束符    
end;

#调用存储过程。可以根据自己的需求定义参数
CALL myLee6(‘Lee’, @sex);
#打印出参数
SELECT @sex;

坑: mysql语句的分隔符默认是;也就是遇到分号就相当于一句mysql语句的结尾,然后会去执行这段mysql;可是在存储过程中很多地方都用到了分号但是语句并没有结束,所以这个时候你需要使用mysql 中的 delimiter重新定义结束语句分隔符,常见的有 delimiter $$。

只有在存储过程中才可以运用流程控制IF、WHILE 等,然后在根据exists判断,执行添加列字段等后续操作增删改查。

2、 存储过程举例。因为springboot不支持在sql脚本中直接添加 delimiter,这个地方需要做 application.properties中进行配置

spring.datasource.separator = $$$

🌰如下:

drop procedure if exists mypro;$$$
create procedure mypro(in a int,in b int,out sum int)
begin
    set sum = a+b;
end;$$$

call mypro(1,2,@s);$$$
select @s;$$$

3、mysql的流程控制IF、、,以及mysql的判断exists。

exists有一个特性就是只会返回true或者false通过它在配合IF或者WHILE进行判断

🌰如下:

drop procedure if exists myLeeTest;
create procedure myLeeTest()
begin
    IF(EXISTS(SELECT * FROM information_schema.TABLES WHERE table_name = "user_info")) THEN
        SELECT 'you';
    ELSE
        SELECT 'meiyou';
    END IF;
end;

CALL myLeeTest();

# 再来一个稍微复杂的,exists执行顺序,由外层执行到内层
drop procedure if exists myLeeTest;
create procedure myLeeTest()
begin
    IF(EXISTS( SELECT id FROM user_info as a WHERE EXISTS(SELECT * FROM user2TestTable as b WHERE b.id = a.id))) THEN
        SELECT 'you';
    ELSE
        SELECT 'meiyou';
    END IF;
end;

CALL myLeeTest();