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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With