我要删除所有具有以下条件的外键。
SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME IN ('Table1', 'Table2') AND CONSTRAINT_NAME LIKE '%FK__%__DL%'
有一个名为的表INFORMATION_SCHEMA.TABLE_CONSTRAINTS,用于存储所有表约束。约束类型FOREIGN KEY也保留在该表中。因此,通过过滤此类型,您可以访问所有外键。
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
FOREIGN KEY
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
如果创建动态查询(用于-DROP对外键进行更改)以更改表,则可以达到更改所有表的约束的目的。
DROP
WHILE(EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME IN ('Table1', 'Table2') AND CONSTRAINT_NAME LIKE '%FK__%__DL%')) BEGIN DECLARE @sql_alterTable_fk NVARCHAR(2000) SELECT TOP 1 @sql_alterTable_fk = ('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']') FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME IN ('Table1', 'Table2') AND CONSTRAINT_NAME LIKE '%FK__%__DL%' EXEC (@sql_alterTable_fk) END
EXISTS 函数及其参数可确保至少有一个外键约束。
EXISTS