Check for column in SQL Table and add if not there

While working on my projects it becomes necessary sometimes to add a column to a table in SQL Server.  My brain goes fuzzy sometimes around SQL as I don't do a lot of hardcore programming in SQL.  Most of my SQL is limited to writing basic Select, Update, Insert and Delete procedures.  So I've determined that with my blog I'm going to put up some of the tips I find along the way to make my life easier and hopefully in the long run I will make someone else's easier as well

So here is how to check if a column exists in a SQL table:

   1:  IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
   2:      WHERE TABLE_NAME = ‘TableName’ AND COLUMN_NAME = ‘TableColumnName’)
   3:      BEGIN
   4:          ALTER TABLE dbo.[TableName]
   5:          ADD [TableColumnName] [int] NULL
   6:      END
   7:  GO

It's not a complicated piece of code to do just takes some remembering or looking for.

Technorati Tags: , ,

del.icio.us Tags: , ,

Posted on 1/8/2008 3:15:08 PM by admin

Permalink | Comments (0) | Post RSSRSS comment feed |

Categories: Software | Programming | SQL Server

Tags: , ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5