This is a problem that arises because the code is compiled first and then executed afterwards. The compiler checks that all columns and tables are available.
Now, the "normal" way to get around these problems is to use dynamic SQL. Something like:
IF OBJECT_ID(''tempdb..#tempTable.Column'') IS NOT NULL
exec sp_executesql N'SELECT Column from #tempTable';
But, this won't work in your case. The problem is that the #temptable
is not understood in the context of the dynamic SQL.
Alas, I don't think you can do what you want with temporary tables. You could do it with a permanent table as:
IF OBJECT_ID('_tempTable.Column') IS NOT NULL
exec sp_executesql N'SELECT Column from _tempTable';
You can probably guess that when I have "temporary" tables in a non-temporary database, I use _
to distinguish them from other tables.
EDIT:
If you want to determine if a column is in a temporary table, then use logic such as this:
select *
from tempdb.sys.columns
where object_id = object_id('tempdb..#mytemptable');
(Courtesy of this answer -- which I note that I had already upvoted.)