By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,391 Members | 1,387 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Check to see weather the column already exists, if not add the column

100+
P: 111
This article will explain you how to check weather a column already exists in a table before you add the column to the table using alter command.

Using the system tables you can check to see weather a column already belongs to a specific table. SYSCOLUMNS is the system table which stores all the table columns information, from this column you can check weather a specific column exists in a specific table.

Example:

if ((SELECT COUNT(*) FROM SYSCOLUMNS WHERE ID = OBJECT_ID('Table_Name') AND Name = 'Column_U_Want_To_Add') < 1 )
Begin
alter table Table_Name add Column_U_Want_To_Add DataType;
End



Here OBJECT_ID takes the Table name as parameter and Name, the column name you want to add.

If the count is more than zero, it indicates that the column already exist with the table. If not then you can add the statement to add the column to the table using the alter command.


Thanks
Bharath Reddy VasiReddy
Sep 9 '09 #1
Share this Article
Share on Google+