前言
1、数据库增量语句:基于现有语句实现增量更新且多次执行增量语句不会影响最终结果。即满足幂等操作。
2、mysql似乎不支持不建立存储过程/函数情况,直接执行块语句。。。这点有些无语
3、本文以存储过程为例。
实现
思路
- 查询是否满足条件
- 执行满足条件的操作
- 删除所有临时变量
实现前提
-- 查询当前库表信息 select * from information_schema. columns where table_schema = (select database()) -- 查询当前库某表信息 select * from information_schema. columns where table_schema = (select database()) and table_name = '表名' -- 查询当前库某表某字段信息 select * from information_schema. columns where table_schema = (select database()) and table_name = '表名' and column_name = '字段名' -- 删除某个表字段(不能有引号) alter table 表名 drop column 字段名; -- 添加某个表字段(不能有引号) alter table 表名 add 字段名 varchar(128) comment '备注等'; -- 修改某个表字段(不能有引号) alter table 表名 change 旧字段名 新字段名 varchar(128) comment '备注等'; -- 实现用户变量 set @变量名='变量值'; select @变量名; -- 实现条件语句(必须在代码块中) if @变量='变量值' then select @变量名; end if; -- 删除存储函数 drop procedure if exists deptproc; -- 创建存储函数 delimiter // create procedure deptproc() begin set @变量名='变量值'; select @变量名; if @变量='变量值' then select @变量名; end if; end// delimiter ; -- 调用存储函数 call deptproc();
增量添加某个字段
-- 删除存储过程 drop procedure if exists testproc; delimiter // -- 创建存储过程 create procedure testproc() begin -- 查询条件 select count(*) into @y from information_schema. columns where table_schema = (select database()) and table_name = '表名' and column_name = '字段名'; -- 查询条件 -- 判断存在 if @y=0 then alter table 表名 add 字段名 varchar(32) comment '备注等'; -- elseif alter table 表名 change 字段名 字段名 varchar(32) comment '备注等'; end if; -- 判断存在 end //delimiter ; -- 调用存储过程 call testproc(); -- 删除存储过程 drop procedure if exists testproc;
增量修改某个字段
-- 删除存储过程 drop procedure if exists testproc; delimiter // -- 创建存储过程 create procedure testproc() begin -- 查询条件 select count(*) into @y from information_schema. columns where table_schema = (select database()) and table_name = '表名' and column_name = '旧字段名'; -- 查询条件 -- 判断存在 if @y=1 then alter table 表名 change 旧字段名 新字段名 varchar(32) comment '备注等'; -- elseif @y =0 then alter table 表名 add 新字段名 varchar(32) comment '备注等'; end if; -- 判断存在 end //delimiter ; -- 调用存储过程 call testproc(); -- 删除存储过程 drop procedure if exists testproc;
增量删除某个字段
-- 删除存储过程 drop procedure if exists testproc; delimiter // -- 创建存储过程 create procedure testproc() begin -- 查询条件 select count(*) into @y from information_schema. columns where table_schema = (select database()) and table_name = '表名' and column_name = '旧字段名'; -- 查询条件 -- 判断存在 if @y=1 then alter table 表名 drop 旧字段名; end if; -- 判断存在 end //delimiter ; -- 调用存储过程 call testproc(); -- 删除存储过程 drop procedure if exists testproc;
总结
1、增量语句写法类似于编写幂等接口,实现多次操作结果一致。
2、实例中多次使用存储函数创建和删除,实在是因为块语句无法脱离存储过程/函数执行
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论