tutorial net
*********WOOOOOOW *********
We're happy to see you're enjoying our races (already 5 pages viewed today)! You can keep checking out by becoming a member of the tutorial net community. It's free!

You will also be able to keep track of your race progress, practice on exercises, and chat with other members.

Share
Go down
Admin
Posts : 200
Join date : 2017-11-11
Age : 27
Location : algeria
View user profilehttp://www.tutorial-net.com

SQL Server - How to check if a column exists in a SQL Server table?

on Wed Apr 11, 2018 5:24 pm
I need to add a specific column if it is does not exist. I have something like this, but it always returns false:
Code:
IF EXISTS(SELECT *
          FROM  INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'myTableName'
                AND COLUMN_NAME = 'myColumnName')
Answers
Code:
SQL Server 2005 onwards:
IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'columnName'
          AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
    -- Column Exists
END
Martin Smith's version is shorter:
Code:
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
    -- Column Exists
END
Back to top
Permissions in this forum:
You cannot reply to topics in this forum