删除带有CHECK CONSTRAINT或MSSQL中的函数

时间:2014-11-26 10:26:54

标签: sql sql-server

我使用以下查询更改了现有表格

ALTER TABLE CodeAccess
    WITH CHECK ADD CONSTRAINT CK_CodeAccess_Code
    CHECK (dbo.chkCodeList('text1', 'text2', [Codes]) = 'True')

现在,我想从 CodeAccess 表中删除函数 chkCodeList(,,)。我尝试过使用

IF EXISTS (
    SELECT * FROM sysobjects WHERE id = object_id(N'dbo.chkCodeList') 
    AND xtype IN (N'FN', N'IF', N'TF')
)
    DROP FUNCTION dbo.chkCodeList
GO

它出现以下错误

Cannot DROP FUNCTION 'dbo.chkCodeList' because it is being referenced by object 'CK_CodeAccess_Code'.

所以,执行......

ALTER TABLE CodeAccess NOCHECK CONSTRAINT CK_CodeAccess_Code

Command(s) completed successfully.

现在,我正在尝试使用第一个查询来更改表格,它给了我......

There is already an object named 'CK_CodeAccess_Code' in the database.

并执行第二个查询,我得到了相同的错误消息......

Cannot DROP FUNCTION 'dbo.chkCodeList' because it is being referenced by object 'CK_CodeAccess_Code'.

我也试过没有前缀 dbo

那么,如何删除函数 chkCodeList()

1 个答案:

答案 0 :(得分:1)

尝试删除约束而不是NOCHECK。也就是说,drop the constraint -> drop the function喜欢

ALTER TABLE CodeAccess  
DROP CONSTRAINT CK_CodeAccess_Code;

DROP FUNCTION dbo.chkCodeList;

在您的情况下,您正在设置NOCHECK但约束仍然存在,因此,当您再次尝试运行ALTER命令时,它会显示名为' CK_CodeAccess_Code'已经存在。