Alter table variable to add primary key get error Incorrect syntax

1k Views Asked by At

I want add a composite primary key constraint to a defined table variable depending on a condition:

DECLARE @tbl TABLE(Col1 int, Col2 int)

IF [myCondition] 
    ALTER TABLE  @tbl ADD CONSTRAINT c PRIMARY KEY(Col1)
ELSE 
    ALTER TABLE  @tbl ADD CONSTRAINT c PRIMARY KEY(Col1,Col2)

But get:

Incorrect syntax near '@tbl'.

1

There are 1 best solutions below

1
On

Alter statements can't be used on table variables.

As an alternative, use a temporary table:

CREATE TABLE #tbl (Col1 int not null, Col2 int not null)

IF [myCondition] 
    ALTER TABLE  #tbl ADD CONSTRAINT c PRIMARY KEY(Col1)
ELSE 
    ALTER TABLE  #tbl ADD CONSTRAINT c PRIMARY KEY(Col1,Col2)