How to check if column exists in SQL Server table


The following queries may help you to check the existing column in SQL Server.

1- Using sys.columns


IF EXISTS( 
            SELECT Name 
            FROM sys.columns
            WHERE Name = N'Col_Name'  
            AND Object_ID = Object_ID(N'Tbl_Name')
)
BEGIN
    print 'true'
END


Note: It will return NULL if the user doesn't have permission to view the metadata because of sys.columns checks user access too.

2- INFORMATION_SCHEMA.columns

  if not exists (select
                     column_name
               from
                     INFORMATION_SCHEMA.columns
               where
                     table_name = 'MyTable'
                     and column_name = 'MyColumn')
    alter table MyTable add MyColumn int

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...