您的位置:首页 > 数据库

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: