Check if a column exists in SQL Server database

1149700 pts.
Tags:
Database
SQL Server
In a SQL Server database, is there a way to check if a column exists in a table? This is what I came up with but it keeps returning false:
IF EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'myTableName'
                 AND COLUMN_NAME = 'myColumnName')
Thanks!
1

Answer Wiki

Thanks. We'll let you know when a new response is added.

I would try using this code instead:

SELECT * FROM sys.columns 
            WHERE Name = N'columnName' AND Object_ID = Object_ID(N'tableName')

Discuss This Question: 3  Replies

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.
  • danieljones
    try this

    IF NOT EXISTS( SELECT NULL

                FROM INFORMATION_SCHEMA.COLUMNS

               WHERE table_name = 'tablename'

                 AND table_schema = 'db_name'

                 AND column_name = 'columnname'THEN

     

      ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';

     

    END IF;

    2,840 pointsBadges:
    report
  • edwinjhoffer

    Or you can try the below code:

    IF COL_LENGTH('tableName', 'columnName') IS NOT NULL

    3,740 pointsBadges:
    report
  • AjitK29
    You can also try:

    IF COL_LENGTH('table_name','column_name') IS NOT NULL
    BEGIN
    PRINT 'Your Column Exists'
    END

    2,545 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

Thanks! We'll email you when relevant content is added and updated.

Following

Share this item with your network: