SQL循环清除表数据
2015-06-16 10:14
549 查看
SQL循环执行清除表数据语句
最近项目经常需要清库测试 但是一个个 truncate 很慢 浪费时间 所以写了个 sql批量清除表数据 这样方便下次使用 灵活性也很高 语句不仅可以 用来清除数据 也可以 批量update delete等逻辑:
根据 字符拆分 字符串 获取每次执行语句的 表名
根据 split 获取字符串内有多少个表 也就是循环的次数
每次循环 先获取本次 执行语句的表名 执行语句 然后再substring下 去除这次执行过的表名 直到循环结束
--定义-- declare @i int --循环变量 declare @length int --循环次数 declare @tableList varchar(Max) --需要循环的表字符串 declare @split varchar(Max) --分割字符串字符 declare @tableName varchar(Max) --执行语句的表名
--初始-- set @i=0 set @tableList='ATable,BTable,CTable ' set @split=',' set @tableList=ltrim(rtrim(@tableList)) --清除字符串 左右空格 set @length=(select len(@tableList)-len(REPLACE(@tableList,@split,''))) --计算需要循环的次数
一开始写时 执行语句那里 直接写 truncate table @tableName
这样肯定不行的 因为@tableName是 varchar类型的变量 执行的时候相当于 truncate table ‘表名’ 所以报错 然后用了exec() 动态执行语句
while(@i<@length+1) --循环语句 begin if(charindex(@split,@tableList)=0) --判断是否只有一张表 begin set @tableName=@tableList end else begin set @tableName=substring(@tableList,0,charindex(@split,@tableList)) --截取 字符串中从开始到第一个@split的字符 获取表名 end exec('truncate table '+@tableName) --执行语句 set @tableList=substring(@tableList,charindex(@split,@tableList)+1,len(@tableList)) --去除已经执行过的表名 set @i=@i+1 end
相关文章推荐
- redis主从配置、分片
- Mysql 下载地址
- SQL 生成6位随机数并MD5加密输出
- MySQL 索引解析
- Oracle导入/导出数据
- C#/.Net 中快速批量给SQLite数据库插入测试数据
- sql中delete,drop ,truncate都代表删除,3者的区别总结
- 【MySql】 BlackHole :黑洞引擎
- ORACLE
- sql中复合组建解析
- mysql基于BLACKHOLE复制基础的各种架构
- hive sql优化
- SQL语句到底是怎么执行的?
- postgresql stream 模式搭建
- Slave_SQL_Running: No mysql同步故障解决方法
- Redis配置文件介绍
- mysql 主从复制
- MySQL出了门,Percona在左,MariaDB在右
- liunx环境下安装redis
- ActiveRecord多数据库配置