如何仅在sql server中存在外键约束?

我可以删除一个表,如果它存在使用下面的代码,但不知道如何做一个约束:

IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'TableName') AND type = (N'U')) DROP TABLE TableName go 

我也使用这个代码添加约束:

 ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT [FK_TableName_TableName2] FOREIGN KEY([FK_Name]) REFERENCES [dbo].[TableName2] ([ID]) go 
 IF (OBJECT_ID('FK_TableName_TableName2', 'F') IS NOT NULL) BEGIN ALTER TABLE dbo.TableName DROP CONSTRAINT FK_TableName_TableName2 END 

这比现在提出的解决scheme简单得多:

 IF (OBJECT_ID('dbo.FK_ConstraintName', 'F') IS NOT NULL) BEGIN ALTER TABLE dbo.TableName DROP CONSTRAINT FK_ConstraintName END 

如果您需要删除另一种types的约束,则这些是在第二个参数位置中传递给OBJECT_ID()函数的适用代码:

 C = CHECK constraint D = DEFAULT (constraint or stand-alone) F = FOREIGN KEY constraint PK = PRIMARY KEY constraint UQ = UNIQUE constraint 

您也可以不使用第二个参数来使用OBJECT_ID。

这里的完整types列表:

对象types:

 AF = Aggregate function (CLR) C = CHECK constraint D = DEFAULT (constraint or stand-alone) F = FOREIGN KEY constraint FN = SQL scalar function FS = Assembly (CLR) scalar-function FT = Assembly (CLR) table-valued function IF = SQL inline table-valued function IT = Internal table P = SQL Stored Procedure PC = Assembly (CLR) stored-procedure PG = Plan guide PK = PRIMARY KEY constraint R = Rule (old-style, stand-alone) RF = Replication-filter-procedure S = System base table SN = Synonym SO = Sequence object 

适用于:通过SQL Server 2014的SQL Server 2012。

 SQ = Service queue TA = Assembly (CLR) DML trigger TF = SQL table-valued-function TR = SQL DML trigger TT = Table type U = Table (user-defined) UQ = UNIQUE constraint V = View X = Extended stored procedure 

如果你知道实际约束的名字,詹姆斯的答案就可以正常工作。 棘手的是,在传统和其他现实世界的情况下,你可能不知道约束被称为什么。

如果是这种情况,您可能会创build重复的约束,以避免您可以使用:

 create function fnGetForeignKeyName ( @ParentTableName nvarchar(255), @ParentColumnName nvarchar(255), @ReferencedTableName nvarchar(255), @ReferencedColumnName nvarchar(255) ) returns nvarchar(255) as begin declare @name nvarchar(255) select @name = fk.name from sys.foreign_key_columns fc join sys.columns pc on pc.column_id = parent_column_id and parent_object_id = pc.object_id join sys.columns rc on rc.column_id = referenced_column_id and referenced_object_id = rc.object_id join sys.objects po on po.object_id = pc.object_id join sys.objects ro on ro.object_id = rc.object_id join sys.foreign_keys fk on fk.object_id = fc.constraint_object_id where po.object_id = object_id(@ParentTableName) and ro.object_id = object_id(@ReferencedTableName) and pc.name = @ParentColumnName and rc.name = @ReferencedColumnName return @name end go declare @name nvarchar(255) declare @sql nvarchar(4000) -- hunt for the constraint name on 'Badges.BadgeReasonTypeId' table refs the 'BadgeReasonTypes.Id' select @name = dbo.fnGetForeignKeyName('dbo.Badges', 'BadgeReasonTypeId', 'dbo.BadgeReasonTypes', 'Id') -- if we find it, the name will not be null if @name is not null begin set @sql = 'alter table Badges drop constraint ' + replace(@name,']', ']]') exec (@sql) end 
 IF (OBJECT_ID('DF_Constraint') IS NOT NULL) BEGIN ALTER TABLE [dbo].[tableName] DROP CONSTRAINT DF_Constraint END 

在SQL Server 2016中,您可以使用DROP IF EXISTS:

 CREATE TABLE t(id int primary key, parentid int constraint tpartnt foreign key references t(id)) GO ALTER TABLE t DROP CONSTRAINT IF EXISTS tpartnt GO DROP TABLE IF EXISTS t 

请参阅http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016.aspx

 ALTER TABLE [dbo].[TableName] DROP CONSTRAINT FK_TableName_TableName2 
 Declare @FKeyRemoveQuery NVarchar(max) IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')) BEGIN SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']' FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName') EXECUTE Sp_executesql @FKeyRemoveQuery END 

我认为这对你有帮助

  DECLARE @ConstraintName nvarchar(200) SELECT @ConstraintName = KCU.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME WHERE KCU.TABLE_NAME = 'TABLE_NAME' AND KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME' IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + @ConstraintName) 

它将根据特定的表和列删除外键约束。

您可以使用这些查询来查找您的表的所有FK。

 Declare @SchemaName VarChar(200) = 'Schema Name' Declare @TableName VarChar(200) = 'Table name' -- Find FK in This table. SELECT 'IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' + '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']' + ''') AND parent_object_id = OBJECT_ID(N''' + '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' + 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '.[' + OBJECT_NAME(FK.parent_object_id) + '] DROP CONSTRAINT ' + FK.name , S.name , O.name, OBJECT_NAME(FK.parent_object_id) FROM sys.foreign_keys AS FK INNER JOIN Sys.objects As O ON (O.object_id = FK.parent_object_id ) INNER JOIN SYS.schemas AS S ON (O.schema_id = S.schema_id) WHERE O.name = @TableName And S.name = @SchemaName -- Find the FKs in the tables in which this table is used SELECT ' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' + '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']' + ''') AND parent_object_id = OBJECT_ID(N''' + '[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' + ' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '.[' + OBJECT_NAME(FK.parent_object_id) + '] DROP CONSTRAINT ' + FK.name , S.name , O.name, OBJECT_NAME(FK.parent_object_id) FROM sys.foreign_keys AS FK INNER JOIN Sys.objects As O ON (O.object_id = FK.referenced_object_id ) INNER JOIN SYS.schemas AS S ON (O.schema_id = S.schema_id) WHERE O.name = @TableName And S.name = @SchemaName 

在这个问题上接受的答案似乎并不适用于我。 我用一个稍微不同的方法取得了同样的结果:

 IF (select object_id from sys.foreign_keys where [name] = 'FK_TableName_TableName2') IS NOT NULL BEGIN ALTER TABLE dbo.TableName DROP CONSTRAINT FK_TableName_TableName2 END