最近在做假資料時經常需要刪除一些表中的內容。但是:
設置外鍵後,想刪除表中的數據無法刪除,這時需刪除外鍵後重建,
或找到外鍵後用 alter table 表名 nocheck 外鍵名 來暫時屏蔽外鍵,然後刪除。
乾脆寫個存儲過程,設置外鍵的開關。
exec fk_switch '表名',0 屏蔽外鍵
exec fk_switch '表名',1 重啓外鍵
/* Usage:
exec fk_switch 'tableName',0
delete tableName where fieldName = 'abc'
-- truncate table tableName
exec fk_switch 'tableName',1
*/
Create proc fk_switch @tableName varchar(20),@status bit
As
declare @fk varchar(50),@fktable varchar(20)
declare @s varchar(1000)
declare cur cursor for
select b.name as fkname,c.name as fktablename
from sysforeignkeys a
join sysobjects b on a.constid = b.id
join sysobjects c on a.fkeyid = c.id
join sysobjects d on a.rkeyid = d.id
where d.name = @tableName
open cur
fetch next from cur into @fk,@fktable
while @@fetch_status = 0
begin
if @status = 0
begin
set @s = 'alter table '+@fktable+' nocheck constraint '+ @fk
print @s
end
else
begin
set @s = 'alter table '+@fktable+' check constraint '+ @fk
print @s
end
exec(@s)
fetch next from cur into @fk,@fktable
end
close cur
deallocate cur
go
--以下爲測試:
create table A (id int primary key)
go
create table B(id int,
constraint fk_B_A foreign key (id) references A (id))
go
create table C(id int,
constraint fk_C_A foreign key (id) references A (id))
go
insert A values (1)
insert B values(1)
insert C values (1)
--1:
delete a
/*****
服務器: 消息 547,級別 16,狀態 1,行 1
DELETE statement conflicted with COLUMN REFERENCE constraint 'fk_B_A'. The conflict occurred in database 'pubs', table 'B', column 'id'.
The statement has been terminated.
*******/
--2:
begin tran
exec fk_switch 'A',0
delete A
exec fk_switch 'A',1
rollback
/*
alter table B nocheck constraint fk_B_A
alter table C nocheck constraint fk_C_A
(所影響的行數爲 1 行)
alter table B check constraint fk_B_A
alter table C check constraint fk_C_A
*/
--3: 清除測試表
drop table A,B,C
go