SQL - If Field Exists Or not
Posted on 2013-11-06
I have 2 databases, one is a newer version with additional fields and the other doesn't have these new fields.
I just want to create one query for use with both database since it's same report. I do not want to have 2 sets of query to toggle between one or the other. Anyway I can check if field exists and if it does, use that field else put a "Null"?
New Database table (Employee)
SELECT ID, NAME, DEPT, PHONE, EMAIL, MOBILE FROM EMPLOYEE
Older Database table (Employee)
SELECT ID, NAME, DEPT, PHONE FROM EMPLOYEE
I am missing Email and Mobile from the older database. When I query the older database, it would throw me an error stating that Email and Mobile doesn't exists. How could I set it with one select statement to use a condition to check if field exists or not?
I found a few examples online to toggle, but would like to not have to toggle. Can something like this be done?
SELECT ID, NAME, DEPT, PHONE, CASE WHEN COL_LENGTH('EMPLOYEE', 'EMAIL') IS NOT NULL THEN 'EMAIL' ELSE 'NULL' END AS EMAIL, CASE WHEN COL_LENGTH('EMPLOYEE', 'MOBILE') IS NOT NULL THEN 'MOBILE' ELSE 'NULL' END AS MOBILE