如何使用T-SQL删除SQL Server 2000中的表上的所有外键约束?
答案 0 :(得分:15)
如果只是禁用约束是一个选项,您可以使用:
ALTER TABLE myTable NOCHECK CONSTRAINT all
然后您可以使用以下方式重新启用它们:
ALTER TABLE myTable WITH CHECK CHECK CONSTRAINT all
如果要在所有表中禁用约束,可以使用:
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
-- enable all constraints
exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
问题中的更多内容:Can foreign key constraints be temporarily disabled using TSQL?
但如果您需要永久删除约束,则可以使用this script posted on databasejurnal.com。
只需略微修改它即可删除外键
create proc sp_drop_fk_constraints
@tablename sysname
as
-- credit to: douglas bass
set nocount on
declare @constname sysname,
@cmd varchar(1024)
declare curs_constraints cursor for
select name
from sysobjects
where xtype in ('F')
and (status & 64) = 0
and parent_obj = object_id(@tablename)
open curs_constraints
fetch next from curs_constraints into @constname
while (@@fetch_status = 0)
begin
select @cmd = 'ALTER TABLE ' + @tablename + ' DROP CONSTRAINT ' + @constname
exec(@cmd)
fetch next from curs_constraints into @constname
end
close curs_constraints
deallocate curs_constraints
return 0
答案 1 :(得分:5)
在这里:(未在SQL2000上测试,但应该没问题)
生成'禁用':
SELECT 'IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N''[dbo].' + FK +''')
AND parent_object_id = OBJECT_ID(N''[dbo].' + PT + '''))
ALTER TABLE ' + PT + ' NOCHECK CONSTRAINT ' + FK + ';'
FROM
(SELECT
OBJECT_NAME(constraint_object_id) as FK,
OBJECT_NAME(parent_object_id) as PT
FROM [sys].[foreign_key_columns] ) T
ORDER BY FK
生成'启用':
SELECT 'ALTER TABLE ' + PT + ' WITH CHECK CHECK CONSTRAINT ' + FK + ';'
FROM
(SELECT
OBJECT_NAME(constraint_object_id) as FK,
OBJECT_NAME(parent_object_id) as PT
FROM [sys].[foreign_key_columns] ) T
ORDER BY FK
更新:哎呀,我以为你想要所有表格:)你可以修改上面的单个表格。
答案 2 :(得分:2)
我认为你会发现在SQL Server 2000中没有简单的方法来删除对表的约束。也就是说,有很多人编写了可以识别和删除/禁用/重新创建外键约束的脚本。一个例子是http://www.mssqltips.com/tip.asp?tip=1376 - 但我还没有在SQL Server 2000上测试它。
编辑:这是另一个为您生成删除/创建脚本的example。