;

How to Check if a Column Exists or Not in a Table in SQL Server


Tutorialsrack 13/11/2023 SQL SQL Server

In this article, you’ll learn how to check if a column exists or not in a table in SQL Server. There are different ways to check if a column exists or not in a table in SQL Server. I hope you all know how to add a new column to an existing table in SQL Server. 

Here are some ways to check as follows:

  • Using Information_Schema

  • Using sys.columns

  • Using Col_Length

1. Using Information_Schema

Example - Using Information_Schema
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName' AND COLUMN_NAME = 'YourColumnName')
    PRINT 'Column exists'
ELSE
    PRINT 'Column does not exist';

2. Using sys.columns

Example - Using sys.columns
IF EXISTS (SELECT 1 FROM sys.columns WHERE Name = N'YourColumnName' AND Object_ID = Object_ID(N'YourTableName'))
    PRINT 'Column exists'
ELSE
    PRINT 'Column does not exist';

3. Using Col_Length

Example - Using Col_Length
IF COL_LENGTH('YourTableName', 'YourColumnName') IS NOT NULL
    PRINT 'Column Exists'
ELSE
    PRINT 'Column doesn''t Exists'

I hope this article will help you to understand how to check if a column exists or not in a table in SQL Server.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags