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?
A more concise version
IF COL_LENGTH('table_name','column_name') IS NULL BEGIN /* Column does not exist or caller does not have permission to view the object */ END
The point about permissions on viewing metadata applies to all answers, not just this one.
Note that the first parameter table name to
COL_LENGTH can be in one, two, or three part name format as required.
An example referencing a table in a different database is:
One difference with this answer, compared to using the metadata views, is that metadata functions, such as
COL_LENGTH, always only return data about committed changes, irrespective of the isolation level in effect.
Tweak the below to suit your specific requirements:
if not exists (select column_name from INFORMATION_SCHEMA.columns where table_name="MyTable" and column_name="MyColumn") alter table MyTable add MyColumn int
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?