MSSQL adding a new column and set foreign key

In SQL server or MSSql ( myLittleAdmin for SQL Server) things are a bit different than MySQL. The syntax will be different in many cases. I had this issue when adding a new column and set a foreign key.

Let's say you have a table with name Employee and you forgot to add a column named CompanyID during the time of table creation. One way to do it as follows.

First add a new column named CompanyID to the table  Employee as follows.

 alter table Employee add CompanyID int not null


Now set the foreign key as shown below


 ALTER TABLE Employees 
 ADD CONSTRAINT FK_Company_UserID 
 FOREIGN KEY (CompanyID) 
 REFERENCES Company(ID);

Comments