SQL Server: If Column Exists

Just like If Table Exists function we can perform operations on If column Exists. Here is the script.
IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N'columnName' AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
 -- Perform something
END

Dynamic
DECLARE @TableName Varchar(50)
DECLARE @ColumnName Varchar(50)
SET @TableName = 'Mytable'
SET @ColumnName = 'Col3'

DECLARE @sql varchar(5000)

set @sql =    'IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N'''+@ColumnName+''' AND Object_ID = Object_ID(N'''+'dbo.'+@TableName+'''))
            BEGIN
                ALTER TABLE Mytable DROP COLUMN '+ @ColumnName +
            ' END'

EXEC(@sql)

No comments:

Post a Comment