How do I drop all foreign-key constraints on a table in Sql Server 2000?
如何使用T-SQL删除SQL Server 2000中表的所有外键约束?
如果只禁用约束是这里的一个选项,则可以使用:
1 | ALTER TABLE myTable NOCHECK CONSTRAINT ALL |
然后,您可以使用以下方法重新打开它们:
1 | ALTER TABLE myTable WITH CHECK CHECK CONSTRAINT ALL |
如果要禁用所有表中的约束,可以使用:
1 2 3 4 5 | -- disable all constraints EXEC sp_msforeachtable"ALTER TABLE ? NOCHECK CONSTRAINT all" -- enable all constraints EXEC sp_msforeachtable"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" |
更多的问题是:外键约束是否可以使用TSQL临时禁用?
但如果需要永久删除约束,可以使用databasejurnal.com上发布的这个脚本。
稍微修改一下,只删除外键
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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 |