Prevent selection of column if it does not exist

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

Database1

  • Do I need to create an Index manually when setting up a foreign key?
  • Values controlled by foreign keys
  • Is Amazon SQS a good tool for handling analytics logging data to a database?
  • MS SQL: One Large, Multi-Column dbo.Person table or Multiple Subsets With Multiple Joins?
  • Trying to compose a Stored Procedure at SQL server with programmer logic but not working
  • SQL Server - Concatenate all child IDs into delimited string in parent record
  • _________  _____________________   _______________
    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!!

    2 Solutions collect form web for “Prevent selection of column if it does not exist”

    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
    

    use case statement

    SELECT 
            ID,[Description],CASE WHEN @DB = 'Database1' THEN Class ELSE Type END
        FROM table 
    
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.