Wednesday, February 27, 2019

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?



Answer



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

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...