我正在尝试创建一个脚本以便在 SQL Express 2008 R2 中创建一个表,如下所示:
IF (EXISTS (SELECT * FROM sys.tables WHERE name='Table' AND [type]='U')) BEGIN
DROP TABLE Table
END
GO
CREATE TABLE Table (
col DATETIMEOFFSET CONSTRAINT DF_Table_col DEFAULT GETUTCDATE()
)
GO
我正在尝试遵循创建可以在我的项目的此发布周期中重新执行的脚本的做法。但问题是我忘记在删除表“Table”之前删除默认约束 DF_Table_col,我将其写为:
IF (EXISTS (SELECT * FROM sys.default_constraints WHERE name='DF_Table_col')) BEGIN
ALTER TABLE Table DROP CONSTRAINT DF_Table_col
END
GO
现在,如果我尝试重新运行脚本,则会收到以下错误:
Msg 2714, Level 16, State 5, Line 1
There is already an object named 'DF_Table_col' in the database.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
如何摆脱孤立约束 DF_Table_col?
我尝试将此孤儿绑定回同名的新表,如下所示:
exec sp_bindefault 'DF_Table_col', 'Table.col'
但它给了我以下错误:
Msg 15050, Level 11, State 1, Procedure sp_bindefault, Line 108
Cannot bind default 'DF_Table_col'. The default must be created using the CREATE DEFAULT statement.