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

NUnit : Introduction

There are several unit test tools in the market, but one of them is NUnit, the most popular tool for doing unit testing. So in this tutorial...