1

I have 2 tables of the same format in 2 separate databases.

Database1

_________  _____________________   _______________
Code(int)   Description(varchar)    Class(varchar)
_________  _____________________   ________________

Database2

_________  _____________________   ___________
Code(int)   Description(varchar)    Type(int)
_________  _____________________   ___________

I wish to write a generic query for my C# application which retrieves the values from both databases. I wrote the following query

DECLARE @DB = 'Database1'

IF(@DB = 'Database1')
BEGIN

SELECT 
    ID,[Description],Class
FROM MyTable

END

ELSE
BEGIN

SELECT 
    ID,[Description],Type
FROM MyTable

END

However the above query throws an error either for columns Class or Type when run for Database2 or Database1 respectively.

PS: I am making the connections with the DB correctly and also setting the parameter @DB accordingly. The logic is to run this query twice, once for Database1 and fetch the respective MyTable with Class column and second time for Database2 and fetch the respective MyTable with Type column.

I wish to know is it in any way possible to achieve what I am trying to do. Thanks in advance!!

1

2 Answers 2

1

This won't work, since:

The entire request (batch) is parsed and compiled. If an error occurs at this stage, the requests terminates with a compilation error

source

You can try dynamic sql:

IF @DB = 'Database1'
BEGIN
    execute sp_sqlexec 
    'SELECT ID,[Description],[Class]
    FROM MyTable;';
END
ELSE
BEGIN
    execute sp_sqlexec 
    'SELECT ID,[Description],[Type]
    FROM MyTable;';
END
0

use case statement

SELECT 
        ID,[Description],CASE WHEN @DB = 'Database1' THEN Class ELSE Type END
    FROM table 
1
  • convert( varchar,CASE WHEN @DB = 'Database1' THEN Class ELSE Type END )
    – Adi
    Aug 30, 2014 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.