'SQL - Incorrect Syntax, expecting ID or QUOTED_ID

I'm new to SQL and I'm trying to remove a constraint from a table.

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

I get the above error when hovering over the last usage of @constraintName. Printing out @constraintName gives me the value of the constraint that I want to drop. Any help would be appreciated.



Solution 1:[1]

Thanks to Illya Bursov's comment, I found this solution to work

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 spottedmahn