The goal I am trying to accomplish is to query from a table that is determined dynamically. Below is an example syntax of what I am trying to accomplish.
if exists (select * from tbl_first_option)
set @tbl = tbl_first_option
else
set @tbl = tbl_second_option
-- complex statement that selects from table
select * from @tbl
So instead of duplicating the complex statement I can use @tbl
. If there are better/easier ways of doing this please let me know.
3条答案
按热度按时间dauxcl2d1#
You can actually do this without dynamic SQL, assuming the two tables have the same columns (or you can add/remove columns to match)
plicqrtu2#
You need a dynamic SQL query like
tf7tbtn23#
Yes there is the easiest way that you can use and its CASE statement which will be as
This query will work on the first table if it's available and from the second table if it's not going to the first table.