Sql-server – Reusing query for duplicate tables

sql server

I have Database A & Database B. Both have a User table.

I need to write one stored procedure that will retrieve the data from the correct table depending on a @Parameter passed in.

The idea of the query (data needing returned) in the stored proc needed:

SELECT * FROM dbA.User || OR || SELECT * FROM dbB.User

I have found the following ways to accomplish this but I want to minimize duplicate code nor add performance slowness/overhead.

Possibilities on my list:

  1. Dynamic SQL – harder to maintain, adds overhead in that my
    understanding cannot define execution plans
  2. Create a duplicate proc or If/Else inside proc – duplicate code
    never good
  3. Table value function – not sure of a way to do this using it as I
    can't use dynamic SQL here or If/Else to tell which query to run.

At this point I am leaning towards Option #2, duplicate code, with the understanding the database setup needs to be better if we want to avoid duplicating code.

I am not saying this is a good database setup, but it is what I am faced with. I have no control over combining database A & B or changing the structure to only have one User table.

Is there any other way to take care of this issue? Or thoughts on my approach?

Best Answer

Let's assume the value of @Parameter is dbA or dbB

SELECT * FROM dbA.User where @Parameter = 'dbA'
UNION ALL
SELECT * FROM dbB.User where @Parameter = 'dbB'