Thursday, February 5, 2009

Add a New Column on an Existing Table as a Foreign Key

In this script example, I needed to add a foreign key column onto an existing table. The table did not contain data


ALTER TABLE [FirstTable]
ADD NewKey_ID uniqueidentifier not null,
CONSTRAINT fk_Campaign_ID FOREIGN KEY (NewKey_ID )
REFERENCES SecondTable (NewKey_ID )

Set an Existing Column as the Primary Key

The column that becomes a primary key must be a uniqueidentity column and must not allow nulls.

Here's the script:

ALTER TABLE [MyTable]
ADD CONSTRAINT pk_MyTable PRIMARY KEY (MyColumn_ID)