I am trying to select the values from column, if the column exist.
This table is going under some modification and some columns are removed and values are extracted to another table.
Query I am using is below. At this stage column can be presented or may be already dropped, so I am doing a column check
IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
SELECT DISTINCT MyColumnName,2
FROM MyTableName
END
Also tried
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'MyColumnName'
AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
SELECT DISTINCT MyColumnName,2
FROM MyTableName
END
But this give me error when the Column is dropped even with the column exist check
Invalid column name 'MyColumnName'
Is there a way to get around this