Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to add a specific column if it does not exist. I have something like the following, but it always returns false:

IF EXISTS(SELECT *           FROM   INFORMATION_SCHEMA.COLUMNS           WHERE  TABLE_NAME = 'myTableName'                  AND COLUMN_NAME = 'myColumnName')  

How can I check if a column exists in a table of the SQL Server database?

like image 930
Maciej Avatar asked Sep 25 '08 12:09

Maciej


People also ask

How do I check if a column exists in a stored procedure in SQL Server?

Use the COL_LENGTH system function! You basically just pass the name of the table your interested in, and the name of the column within that table you want to check. This function returns the defined length of the column in bytes, if that column exists. If the column does not exist, the function returns NULL.


1 Answers

SQL Server 2005 onwards:

IF EXISTS(SELECT 1 FROM sys.columns            WHERE Name = N'columnName'           AND Object_ID = Object_ID(N'schemaName.tableName')) BEGIN     -- Column Exists END 

Martin Smith's version is shorter:

IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL BEGIN     -- Column Exists END 
like image 191
Mitch Wheat Avatar answered Oct 06 '22 08:10

Mitch Wheat