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=0set @tableList='ATable,BTable,CTable 'set @split=','set @tableList=ltrim(rtrim(@tableList)) --清除字符串 左右空格set @length=(select len(@tableList)-len(REPLACE(@tableList,@split,''))) --计算需要循环的次数
一开始写时 执行语句那里 直接写 truncate table @tableName
这样肯定不行的 [email protected] varchar类型的变量 执行的时候相当于 truncate table ‘表名’ 所以报错 然后用了exec() 动态执行语句
while(@i<@length+1) --循环语句beginif(charindex(@split,@tableList)=0) --判断是否只有一张表beginset @tableName=@tableListendelsebegin set @tableName=substring(@tableList,0,charindex(@split,@tableList)) --截取 字符串中从开始到第一个@split的字符 获取表名endexec('truncate table '+@tableName) --执行语句set @tableList=substring(@tableList,charindex(@split,@tableList)+1,len(@tableList)) --去除已经执行过的表名 set @i=@i+1end
- 1楼baidu_29074695昨天 20:56
- 厉害
- Re: u01341983810小时前
- 回复baidu_29074695n谢谢夸奖