简体   繁体   中英

Case expression to check if column exists throws invalid column name error

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?

I believe i have solved my troubles thanks to the workaround provided by @MartinSmith ( https://dba.stackexchange.com/questions/66741/why-cant-i-use-a-case-statement-to-see-if-a-column-exists-and-not-select-from-i/66755#66755 )

I ended up using an alternative version of the workaround provided, linked by the poster of @MartinSmith's solution, but the results seem to be what i was expecting.

Regarding the Only one expression can be specified in the select list when the subquery is not introduced with EXISTS error, it was being caused by me trying to SELECT two columns in the subquery. Solution came from here: https://stackoverflow.com/a/7684626/18191554

Now, my code is as follows:

select
.
.
.
.
(select (SELECT [ABC]
           from dbo.tableName 
           where ID = temp.ID])
           from (select '' as [ABC]) as dummy)
           
        as 'XYZ',

.
.
.
from tableName

where ABC is the column that may or may not exist.

Thanks to everyone involved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM