34,588
社区成员
发帖
与我相关
我的任务
分享
-- 如果要稳妥,先查下删除的表是否正确
exec tempdb..sp_msforeachtable '
if object_id(''?'') in ( object_id(''要保留的表1''), object_id(''要保留的表2'') ) return;
print ''?'''
-- 先把约束禁用(这样主外键不再束缚我们的操作顺序了,缺点是如果之前有禁用的约束,则后面的启用也会启用)
exec tempdb..sp_msforeachtable 'alter table ? nocheck constraint all'
-- 删除
exec tempdb..sp_msforeachtable '
if object_id(''?'') in ( object_id(''要保留的表1''), object_id(''要保留的表2'') ) return;
-- 如果 truncate 失败,使用 delete,这样无法 truncate 的表也能处理了
begin try
truncate table ?
end try
begin catch
delete from ?
end catch'
-- 完成后启用约束
exec tempdb..sp_msforeachtable 'alter table ? check constraint all'
--清空所有除 t1, t2 之外的表的所有记录
EXEC sp_msforeachtable 'if "?" not in ("t1","t2") truncate table ? '
declare @tablename NVARCHAR(100)
declare auth_cur cursor for
SELECT b.name
FROM sysindexes AS a
INNER JOIN sys.tables AS b ON b.object_id = a.id
WHERE indid IN ( 0, 1 );
open auth_cur
fetch next from auth_cur into @tablename
while (@@fetch_status=0)
begin
IF(@tablename<>'test') --排除个别表
BEGIN
EXEC('delete from '+@tablename)
END
fetch next from auth_cur into @tablename
end
close auth_cur
deallocate auth_cur
--t1,t2 请修改成你对应的表名
--清空所有除 t1, t2 之外的表的所有记录
EXEC sp_msforeachtable 'if "?" not in ("t1","t2") print "truncate table ?" '
--输出的结果, 你审查一下没有问题, 复制出来再执行就可以了