2

I am trying to get data from table based on parameters,

Declare @Loadtype varchar(10) = 'A'

Select *
from TableA (if  @Loadtype = 'A')

Select *
from TableB (if  @Loadtype = 'B')

Not sure how I can achieve this.

Many Thanks, Uday

4
  • Use case statement – Learning_DBAdmin Feb 2 at 16:56
  • There's no CASE statement in SQL Server. Perhaps you were thinking of some other RDBMS? (I know there's a CASE statement in ANSI/ISO SQL, in addition to the the CASE expression). Or did you mean SQL Server's CASE expression? – Tibor Karaszi Feb 2 at 17:10
  • Oh, case expression and statement, sqlshack.com/case-statement-in-sql – Learning_DBAdmin Feb 2 at 17:42
  • 1
    Why are these different load types in separate tables instead of in the same table with a loadtype column? This will make your life much simpler especially as you add C, D, E... when do you stop adding tables? When you get to Z? – Aaron Bertrand Feb 2 at 18:05
6

You can do a UNION between the two tables and modify the WHERE clause based on the parameter passed (i.e., SELECT from both tables and let the parameter decide whether to return any rows).

Or you can use dynamic SQL, i.e., build a string and execute that string using sp_executesql. Required reading before using dynamic SQL is http://www.sommarskog.se/dynamic_sql.html. Erland even has a section about this particular requirement.

And, you can of course have an IF and do two separate SELECTS, which one depends on the contents of the variable.

To be honest, above "solutions" sucks. I suggest you take a step back and look at the broader picture.

And to make it clear: You can not have a variable or parameter for the table name in a DML command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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