Link to home
Start Free TrialLog in
Avatar of holemania
holemania

asked on

SQL - If Field Exists Or not

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"?

Example:

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
FROM EMPLOYEE
Avatar of sergiomn
sergiomn

The simplest solution would be just to add those 2 missing columns to the old database.

If you're using java, you could also use getMetaData() to get the column count, names and more, so you could have a function to retrieve results from any table, even if you don't know what columns are in it.

Also, if you're executing this query inside any sort of script, you could use a parameter so you can know if execute one or another query.

There are many other aproaches to this, it depends on your needs.
Avatar of holemania

ASKER

Adding the 2 missing columns is a no no for us since when upgrading, it might create issue since the upgrade to the database will attempt to add those 2 fields and may fail.

Probably might have to create 2 queries and just toggle between the 2 depending on which database to connect to.
Avatar of Brendt Hess
Much depends on how you are running this.  However, it is fairly straightforward to get the number of columns for a table.  Here is one example:

DECLARE @tableName sysname
SET @tableName = 'MyTableName'

DECLARE @cols int

SELECT @cols = COUNT(*)
FROM sys.columns AS c
INNER JOIN sys.tables AS t
	ON c.object_id = t.object_id
WHERE t.object_id = OBJECT_ID(@tablename)

Open in new window

If this is a stored procedure, you can check the table, find the number of columns, and see if your version works when the COL_LENGTH check is replaced by  CASE @cols WHEN 6 THEN EMAIL END as email (for example)
ASKER CERTIFIED SOLUTION
Avatar of Sharath S
Sharath S
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks that helped.