I have two tables, where only one column is the same. I am trying to write a stored procedure which pulls a value from a passed-in column name, but one which only exists in one of the tables. This is what I have written:
IF EXISTS(
SELECT identifier FROM TableA WHERE identifier='12345')
SELECT ColumnWhichOnlyExistsInA FROM TableA WHERE identifier='12345'
ELSE
SELECT ColumnWhichOnlyExistsInA FROM TableB WHERE identifier='12345'
This gives me the ‘Invalid column name’ error on the last line, even though the IF statement is true and it should only be pulling stuff from TableA. I’ve noticed that if I replace the bottom two SELECT statements with stored procedures which do the same thing, it works; SQL doesn’t try to execute the one where IF is false.
I want to keep everything in one stored procedure. What would be the best way of doing it?
Your query is failing to COMPILE because the compiler checks that columns to be selected exist in the respective tables – so the IF statement never gets executed.
It works in separate stored procedures because these are compiled on demand at runtime, and thus only the “working” stored proc would be compiled.
To get around the problem use Dynamic SQL