如果一个Table是其他表的外键,那么对该Table的引用列进行Update 或 Insert 会受到很多限制。Disable Foreign Key Constraints with INSERT and UPDATE Statements。
查看FK的信息,主要使用sys.foreign_keys 和 sys.foreign_key_columns 这两个表,辅助表:sys.objects (type=‘F‘),sys.tables,sys.columns
--get FK list select fk.object_id as FK_Object_ID, fk.name as FK_name, pt.name as ParentTable_Name, pc.name as ParentTable_Column_Name, rt.name as ReferencedTable_Name, rc.name as ReferencedTable_Column_Name from sys.foreign_keys fk with(nolock) inner join sys.foreign_key_columns fkc with(nolock) on fk.object_id=fkc.constraint_object_id inner join sys.tables pt with(nolock) on fkc.parent_object_id=pt.object_id inner join sys.columns pc with(nolock) on fkc.parent_object_id=pc.object_id and fkc.parent_column_id=pc.column_id inner join sys.tables as rt with(nolock) on fkc.referenced_object_id=rt.object_id inner join sys.columns rc with(nolock) on fkc.referenced_object_id=rc.object_id and fkc.referenced_column_id=rc.column_id where rt.name=N‘Referenced_Table_name‘ --disable FK constraint ALTER table ParentTable_name nocheck constraint FK_name --enable FK constraint ALTER table ParentTable_name check constraint FK_name
参考MSDN:ALTER TABLE (Transact-SQL)
ALTER TABLE schema_name . table_name [ WITH { CHECK | NOCHECK } ] { CHECK | NOCHECK } CONSTRAINT { ALL | constraint_name [ ,...n ] }
WITH CHECK | WITH NOCHECK
Specifies whether the data in the table is or is not validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for re-enabled constraints.
If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK. We do not recommend doing this, except in rare cases. The new constraint will be evaluated in all later data updates. Any constraint violations that are suppressed by WITH NOCHECK when the constraint is added may cause future updates to fail if they update rows with data that does not comply with the constraint.
The query optimizer does not consider constraints that are defined WITH NOCHECK. Such constraints are ignored until they are re-enabled by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.
{ CHECK | NOCHECK } CONSTRAINT
Specifies that constraint_name is enabled or disabled. This option can only be used with FOREIGN KEY and CHECK constraints. When NOCHECK is specified, the constraint is disabled and future inserts or updates to the column are not validated against the constraint conditions. DEFAULT, PRIMARY KEY, and UNIQUE constraints cannot be disabled.
ALL
Specifies that all constraints are either disabled with the NOCHECK option or enabled with the CHECK option.
参考Post:
How can I list all foreign keys referencing a given table in SQL Server?