-- 禁用所有约束
EXEC sp_msforeachtable
@command1=N'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
-- 删除无外键约束的表中的数据
EXEC sp_msforeachtable
@command1=N'TRUNCATE TABLE ?',
@whereand=N'AND NOT EXISTS(
SELECT rkeyid FROM dbo.sysforeignkeys
WHERE rkeyid=O.id)
AND EXISTS(
SELECT rows FROM dbo.sysindexes
WHERE id=O.id
AND rows>0
AND indid<2)'
-- 删除有外键约束的表中的数据
EXEC sp_msforeachtable
@command1=N'DELETE ?',
@whereand=N'AND EXISTS(
SELECT rows FROM dbo.sysindexes
WHERE id=O.id
AND rows>0
AND indid<2)'
-- 启用所有约束
EXEC sp_msforeachtable
@command1=N'ALTER TABLE ? CHECK CONSTRAINT ALL'