I'm building a Stored Procedure meant to be run daily. Due to how the data is provided me, some days some of the columns necessary for the output are not in the file that's imported to a temporary table.
For the output, the value can be null/empty, but the actual column has to be there.
I've tried the following code:
select
case
when exists(
select * from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tableName' and COLUMN_NAME = 'ABC'
) then ABC
else ''
end
as 'XYZ' from tableName
I know for a fact that in the tests I'm running the column DOES NOT exist, so I'm expecting the SELECT statment to simply return an empty string for column XYZ.
However when running such SELECT statement, I get the following error:
Invalid column name 'ABC'.
Since I know from the start that the column ABC does not exist, I was expecting that the EXISTS(...) would evaluate to FALSE and jump straight to the ELSE statement. However it seems that the column name is still evaluated.
How can I get around this?