一 需求描述
需要将mysql其中一张表的部分字段写入到另一张表中,其余字段给固定值,使用mysql存储过程实现。
二 解决
2.1 什么是存储过程
在大型数据库系统中,一组为了完成特定功能的sql语句集,存储在数据库中,经过第一次编译后再次调用不需要再次编译,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。
实质就是SQL语句的合集,包括了逻辑控制
2.2 存储过程定义
create procedure test1()
begin
流程控制结构
SQL语句集合
end;
2.2.1流程控制结构
2.2.1.1 条件结构
if 条件 then sql语句集合
else if 条件 then sql语句集合
else sql语句集合
当形参中的变量和存储过程中的局部变量同名时,会覆盖形参中的变量
case 语法
1)
case 变量
when 变量取值1 then sql语句集合
when 变量取值2 then sql语句集合
else sql语句集合
end case;
case
when 变量与值1表达式 then sql语句集合
when 变量与值2表达式 then sql语句集合
else
end case;
2.2.1.2 循环结构
while .....end while
loop..... end loop
rerpeat ...... end repeat
2.3 SQL中数据类型转换
2.3.1 cast
cast(字段名 as datatype)
2.3.2 convert
convert(字段名,datatype)
2.3.3 可以转换的数据类型
数值类型 | 表达式 |
---|---|
二进制,同带binary前缀的效果 | BINARY |
字符型,可带参数 | CHAR() |
日期 | DATE |
时间 | TIME |
日期时间型 | DATETIME |
浮点数 | DECIMAL |
整数 | SIGNED |
无符号整数 | UNSIGNED |
2.4 示例
create PROCEDURE iotcollectadd()
BEGIN
#如果备份表存在则将备份表删除
drop table if exists table_backup;
#备份原testtable表中的数据
create table table_backup LIKE testtable;
insert into table_backup select * from testtable;
#读取另一个表中的数据并将其插入该表中,其余字段取固定值
insert into table_backup(column1,column2,column3,column4,column5,column6) (select 60,cast(othertable_column2 as CHAR),othertable_column3,othertable_column3,"1" from othertable);
END;