删除SQL Server 2005
中具有约束的列时出现以下错误。
对象' DF__PlantRecon__Test'取决于专栏'测试'。
该列不是任何键的一部分。但它有一个default
约束,约束有一个预定义的名称。
虽然我已经编写了首先删除约束的代码,但它无效。
注意:我需要先检查约束是否存在。
参考
CODE
IF OBJECT_ID('DF__PlantRecon__Test', 'C') IS NOT NULL
BEGIN
SELECT 'EXIST'
ALTER TABLE [dbo].[PlantReconciliationOptions] drop constraint DF__PlantRecon__Test
END
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME ='DF__PlantRecon__Test')
BEGIN
SELECT 'EXIST'
--drop constraint
ALTER TABLE [dbo].[PlantReconciliationOptions] drop constraint DF__PlantRecon__Test
END
IF EXISTS ( SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[dbo].[PlantReconciliationOptions]') AND name = 'Test')
BEGIN
--drop column
ALTER TABLE [dbo].[PlantReconciliationOptions] DROP COLUMN Test
END
ALTER TABLE PlantReconciliationOptions
ADD Test INT NOT NULL
CONSTRAINT DF__PlantRecon__Test DEFAULT 30
答案 0 :(得分:3)
试
IF OBJECT_ID('DF__PlantRecon__Test') IS NOT NULL
BEGIN
SELECT 'EXIST'
ALTER TABLE [dbo].[PlantReconciliationOptions] drop constraint DF__PlantRecon__Test
END
在你的例子中,你正在寻找一个' C'检查约束,DEFAULT不是。你本来可以改变C'对于一个' D'或者省略所有参数。
如果您的命名与您的命名一致(例如DF__xxx),则删除第二个参数是可接受的选择,以确保删除硬编码约束名称。
以下是您可以传递的OBJECT_ID()对象类型的列表:
AF = Aggregate function (CLR)
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
PK = PRIMARY KEY constraint
P = SQL stored procedure
PC = Assembly (CLR) stored procedure
FN = SQL scalar function
FS = Assembly (CLR) scalar function
FT = Assembly (CLR) table-valued function
R = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S = System base table
SN = Synonym
SQ = Service queue
TA = Assembly (CLR) DML trigger
TR = SQL DML trigger
IF = SQL inline table-valued function
TF = SQL table-valued-function
U = Table (user-defined)
UQ = UNIQUE constraint
V = View
X = Extended stored procedure
IT = Internal table
答案 1 :(得分:1)
解决问题的步骤。