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?
SQL Server 2005 onwards:
Martin Smith's version is shorter:
A good friend and colleague of mine showed me how you can also use an
IF
block with SQL functionsOBJECT_ID
andCOLUMNPROPERTY
in SQL SERVER 2005+ to check for a column. You can use something similar to the following:You can see for yourself here
Tweak the below to suit your specific requirements:
Edit to deal with edit to question: That should work - take a careful look over your code for stupid mistakes; are you querying INFORMATION_SCHEMA on the same database as your insert is being applied to for example? Do you have a typo in your table/column name in either statement?
I'd prefer
INFORMATION_SCHEMA.COLUMNS
over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example,dbo.syscolumns
does still work in SQL 2008, but it's deprecated and could be removed at any time in future.