Announcement

Collapse
No announcement yet.

How to check if column exists in SQL Server table

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to check if column exists in SQL Server table

    Hello,

    I want to check if column exists or not in SQL Server table and need to add a specific column if it does not exist.
    I create a code as follows, but it always returns false:

    Code:
    IF EXISTS(SELECT * FROM   INFORMATION_SCHEMA.COLUMNS
              WHERE  TABLE_NAME = 'myTableName'
                     AND COLUMN_NAME = 'myColumnName')
    So, how can I check if a column exists in a table in SQL Server database?

  • #2
    Hi,

    Execute the following query to check if column exists or not in SQL Server table.

    IF EXISTS(SELECT * FROM sys.columns
    WHERE Name = N'columnName' AND OBJECT_ID = OBJECT_ID(N'tableName'))
    BEGIN
    PRINT 'Your Column Exists'
    END
    To add a specific column if it does not exist in SQL Table.

    IF NOT EXISTS(
    SELECT TOP 1 1
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
    [TABLE_NAME] = 'tableName'
    AND [COLUMN_NAME] = 'columnName')
    BEGIN
    ALTER TABLE [tableName]
    ADD [columnName] INT NULL
    END

    Comment


    • #3
      You can also try:

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

      Comment

      Working...
      X