Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Adding column and foreign key constraint

Author  Topic 

insanepaul
Posting Yak Master

178 Posts

Posted - 2010-10-04 : 10:46:23
1.How do I add a column and foreign key constraint in one line to an existing table?
2. I should set it a default value?

IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('JobQuality') AND NAME='JobTransportationMethodId')
BEGIN
ALTER TABLE JobQuality
ADD JobTransportationMethodId INT CONSTRAINT FK_JobQuality_JobTransportationMethodId FOREIGN KEY(JobTransportationMethodId) REFERENCES JobTransportMethod(JobTransportationMethodId)
END

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-10-04 : 11:01:53
you need to check for existence of fk constraint also before creation.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

insanepaul
Posting Yak Master

178 Posts

Posted - 2010-10-04 : 11:17:32
OK Thanks, I'll setup 2 lots of statements, the first to add the column, the second to add the constraint to it
Go to Top of Page
   

- Advertisement -