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?
Wheat's answer is good, but assumes you do not have any identical table name / column name pairs in any schema or database. To make it safe for that condition use this...
Here is a simple script I use to manage addition of columns in the database:
In this example, the
Name
is theColumnName
to be added andObject_Id
is theTableName
For the people who is checking the column existence to drop it.
In SQL Server 2016 you can use new DIE statements instead of big
IF
wrappersA more concise version
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.There are several ways to check the existence of a column. I would strongly recommend to use
INFORMATION_SCHEMA.COLUMNS
as it is created in order to communicate with user. Consider following tables:and even some other access methods available to check
system catalog.
Also, no need to use
SELECT *
, simply test it byNULL value
Yet another variation...