I am using SQL Server 2008.
Is there a way to select from multiple databases where the column being queried might or might not exist?
My current code is as follows:
SELECT Value FROM [database1].[dbo].[table_name] WHERE Name='job_name' AND EXISTS (SELECT 1 FROM [database1].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='table_name')
UNION
SELECT Value FROM [database2].[dbo].[table_name] WHERE Name='job_name' AND EXISTS (SELECT 1 FROM [database2].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='table_name')
Just to clarify, I am trying to query from two different databases. Both databases should have the same schema, but might not have been fully initialized and so might not contain the table being queried. I am trying to do this in one query.
The names used in a query must exist at the time when the SQL optimizer tries to plan the execution of the query. If they don’t, you will get back rude messages about the relevant table or column not existing. There isn’t any standard way around this. And it is highly unlikely there’s a non-standard way around this either.
At least, no way around it that takes the query text verbatim. If you’re prepared to do the system catalog queries (either through the native system catalog tables or via the information schema, which is more or less standardized), then you can decide how to build the query at runtime, so that it has a maximal chance of succeeding. This is an unusual requirement; few programs are designed to tolerate such deviations from the expected norm for the database to which they connect.