Skip to content
Advertisement

SQL query to use different tables conditionally

I have a stored procedure which uses different tables for a join based on an input parameter. Currently I have to write the SQL query twice (with only the table name difference). Is it possible to combine them so I do not have to repeat SQL query logic twice?

Current code:

One of the possible ways is to store TableA1 / TableA2 data to a temp table first and use the temp table to join inside a complex query. Is there any better way?

Advertisement

Answer

If the two tables have the same structure (as implied by the temp table comment), you can do:

Another alternative is dynamic SQL, but that can be tricky to maintain — because the code looks like a string.

Sometimes, you can do this with a left join as well:

Although this should have good performance, it has the downside that all references to a columns need to use coalesce().

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement