Sunday, March 11, 2012

Dynamic From clause?

How can I get an SP to use one table in the From clause if a condition is true and another table if false? I'd like to avoid creating a "dynamic query," one in which the whole query is built in a string then executed (exec str).

Thank you.

There isn't a really good way.

To avoid Dynamic SQL, the only option is to use an IF statement in your stored procedure to send processing to one select or the other.

If the tables are very similar, you can combine them into a single VIEW and query against that, adjusting the WHERE clause instead (which supports variables).

-Ryan / Kardax

|||That's what I was afraid of... Thank you.|||

You can use 2 separate queries for each condition and combine them with UNION. The fields in the SELECT statement must be similar in this case. Here is an example:

Code Snippet

SELECT col1, col2, col3

FROM Table1

WHERE Condition1

UNION

SELECT col1, col2, col3

FROM Table2

WHERE Condition2

I hope this answers your questions.

Best regards,

Sami Samir

No comments:

Post a Comment