这是在数据库和模式上参数化的。如果没有提供模式,它将清除指定数据库中的所有数据。
通过禁用约束适当地处理具有外键引用的表。如果程序失败(通常不应该这样做),请确保在修复问题原因后成功运行它,这应确保约束检查恢复正常。
如果您在模式之间有外键,这将无法正确处理外键引用,但是,可以很容易地对其进行修改以处理此问题。
create procedure [removeData] (@database_name sysname, @schema_name sysname = null)
as
set nocount on
create table #tables (
TableName varchar(900) not null primary key,
HasFKRef bit not null
);
declare @sql nvarchar(4000),
@table_name varchar(900);
if (db_id(@database_name) is null)
raiserror ('You must at least specify the database name', 16, 1);
set @sql = 'select ''['' + TABLE_CATALOG + ''].['' + TABLE_SCHEMA + ''].['' + TABLE_NAME + '']'' as TableName, (case when exists(select * from [' + @database_name + '].INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc inner join [' + @database_name + '].INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on rc.UNIQUE_CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG and rc.UNIQUE_CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA and rc.UNIQUE_CONSTRAINT_NAME = tc.CONSTRAINT_NAME where tc.TABLE_NAME = t.TABLE_NAME) then 1 else 0 end) as HasFKRef
from [' + @database_name + '].INFORMATION_SCHEMA.TABLES t
where TABLE_TYPE = ''BASE TABLE'' and TABLE_SCHEMA = isnull(@schema_name, TABLE_SCHEMA)';
insert into #tables
exec sp_executesql @sql, N'@schema_name sysname', @schema_name;
declare @curse cursor
set @curse = cursor fast_forward for
select sql from (
select 'alter table ' + TableName + ' nocheck constraint all' as sql, 1 as sort
from #tables
union all
select 'truncate table ' + TableName, 2 as sort
from #tables
where HasFKRef = 0
union all
select 'delete from ' + TableName, 3 as sort
from #tables
where HasFKRef = 1
union all
select 'alter table ' + TableName + ' with check check constraint all', 4 as sort
from #tables
) t
order by sort, sql
open @curse
fetch next from @curse into @sql
while (@@fetch_status = 0)
begin
exec (@sql)
fetch next from @curse into @sql
end
close @curse
GO