in

Bunker Hollow

Matt Williamson's home on the web, welcome.

Sponsored Link

Matt Williamson's Blog

Personal discoveries of an IT professional.

MS SQL Check If Column Exists

The following SQL script checks if a certain column exists in a certain table, then prints some text to the output window.  I'm getting into the best practice habit of creating SQL scripts that can be re-run without any errors and this is useful in checking to see if a column already exists before altering the table and attempting to add the column.

IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE column_name='COLUMNNAME' AND table_name='TABLENAME')

BEGIN

     PRINT 'This column exists!'

END

Comments

 

Narendar Piryani said:

This Works other way round, You will ONLY hit Begin block when column exists, otherwise you need to add NOT statement in front of Exist.

October 27, 2009 12:23 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
Powered by Community Server (Non-Commercial Edition), by Telligent Systems