How to check if a column exists in a table in SQL Server

All topics about programming / development in T-SQL or other languages for SQL Server.
Post Reply
AfterCatch
Posts: 2
Joined: Thu Jul 18, 2019 4:04 pm

Thu Jul 18, 2019 4:11 pm

Does anybody have any code / scripts to check if a column exists in a table of the SQL Server database?

The column is called 'MiddleName' in the table dbo.Users.

Can anybody help please?
Logger
Posts: 1
Joined: Thu Jul 18, 2019 4:12 pm

Thu Jul 18, 2019 4:15 pm

Hi @AfterCatch

This can be achieved by the below...

Code: Select all


IF EXISTS (SELECT * FROM sys.columns 
          WHERE Name = N'MiddleName'
          AND Object_ID = Object_ID(N'dbo.Users'))
BEGIN
    -- Do Something if the Column Exists in the Table.
END

AfterCatch
Posts: 2
Joined: Thu Jul 18, 2019 4:04 pm

Thu Jul 18, 2019 4:16 pm

That works, thank you for the quick response!
Post Reply

Social Media