Pregunta

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

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a dba.stackexchange
scroll top