Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Drop a constraint using a variable

Status
Not open for further replies.

sqlturbo

IS-IT--Management
Mar 11, 2002
67
US

Is it possible drop a constraint on a table by getting the constraint name in a variable and passing that variable to the drop constraint command. Here's an example.

DECLARE @name varchar(10)

SELECT @name = [name] from sysobjects Where xtype = 'F'
and Parent_obj = (SELECT OBJECT_ID('Table1'))

ALTER TABLE Table1
DROP CONSTRAINT @name

When I execute it, I get a "Incorrect syntax near '@name'." error on the Drop Constraint line.

Any ideas? Thanks for any input you may have.
 
Try making the last part dynamic SQL.

Exec (ALTER TABLE Table1
DROP CONSTRAINT + '@name')

I actually learned that very thing from a helpful person on this forum! I would tell you who it was but I have forgotten now. I just wanted to make sure to give as much credit as I good where it belonged[2thumbsup]
 
evaleah is right but the syntax is not quite correct:

Code:
EXEC('ALTER TABLE table1 DROP CONSTRAINT ' + @name)

--James
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top