I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same. For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:
- in DB1:
select p_user from orders - in DB2:
select userpk from orders
Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type
I can't do much about these differences - they are historic - and changing the schema to match is not an option.
I want to be able to run the same SQL statement against all of these databases at once. I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't. For example:
select
case
when COL_LENGTH('orders', 'p_user') IS NOT NULL
then
orders.p_user
else
orders.userpk
end
from orders
This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false. The same thing happens if I use IIF function.
If I simply run
select
case
when COL_LENGTH('orders', 'p_user') IS NOT NULL
then
'orders.p_user'
else
'orders.userpk'
end
then I do get the correct string, which means my condition is correct.
How can I formulate the SQL statement to use one or the other column based on whether the first one exists?
SELECT x AS y FROM legacydb.dbo.OldTable). It would take up "no room" since it needn't actually contain any data of its own.SELECT T.ID, V.DoesNotExist FROM T CROSS JOIN (SELECT NULL) _(DoesNotExist) CROSS APPLY (SELECT DoesNotExist FROM T) Vwill pickDoesNotExistfromTif it exists, andNULLotherwise (you can plug in another column there). Doing this in every single one of your queries is a massive pain, decreases maintainability and has potential performance issues, so I mention it only for completeness.