gpt4 book ai didi

sql - 仅当 SQL Server 中存在外键约束时,如何删除它?

转载 作者:行者123 更新时间:2023-12-01 16:24:57 25 4
gpt4 key购买 nike

我可以使用以下代码删除表(如果存在),但不知道如何对约束执行相同操作:

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('dbo.FK_ConstraintName', 'F') IS NOT NULL)
BEGIN
ALTER TABLE dbo.TableName DROP CONSTRAINT FK_ConstraintName
END

如果您需要删除其他类型的约束,这些是要传递到 OBJECT_ID() 函数的第二个参数位置的适用代码:

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

您还可以使用不带第二个参数的 OBJECT_ID。

类型的完整列表 here :

对象类型:

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 2012 到 SQL Server 2014。

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

关于sql - 仅当 SQL Server 中存在外键约束时,如何删除它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/482885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com