SQL - 不正确的语法,期望ID或QUOTED_ID

时间:2017-07-18 21:00:27

标签: sql-server tsql dynamic-sql

我是SQL的新手,我正在尝试从表中删除约束。

DECLARE @constraintName nvarchar(100)

set @constraintName = (SELECT  OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
WHERE type_desc LIKE '%DEFAULT_CONSTRAINT' AND parent_object_id = OBJECT_ID('dbo.regression_pool_machine'))

ALTER TABLE dbo.regression_pool_machine DROP CONSTRAINT @constraintName

当鼠标悬停在@constraintName的最后一次使用时,我收到上述错误。  打印出@constraintName给出了我想要删除的约束的值。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

感谢Illya Bursov的评论,我找到了这个解决方案

DECLARE @constraintName nvarchar(100)
    DECLARE @sqlCommand varchar(1000)
    set @constraintName = (SELECT  OBJECT_NAME(OBJECT_ID) AS NameofConstraint
    FROM sys.objects
    WHERE type_desc LIKE '%DEFAULT_CONSTRAINT' AND parent_object_id = OBJECT_ID('dbo.regression_pool_machine'))
    SET @sqlCommand = 'ALTER TABLE dbo.regression_pool_machine DROP CONSTRAINT ' + @constraintName
    EXEC (@sqlCommand)