I'm running on SQL Server 2012.
Imagine I have 3 tables (Table1, Table2, Table3) that all have in common 2 fields (ID, WhereParam).
What would be the right way to achieve this?
SELECT ID FROM
(CASE @Var
WHEN "AA" THEN Table1
WHEN "BB" THEN Table2
ELSE Table3)
WHERE "TableSelected".WhereParam = @WhereParam
Using IF
(the proper way)
IF @Var = 'AA'
BEGIN
SELECT ID FROM Table1
-- WHERE ...
END
ELSE IF @Var = 'BB'
BEGIN
SELECT ID FROM Table2
-- WHERE ...
END
ELSE
BEGIN
SELECT ID FROM Table3
-- WHERE ...
END
Other ways (you should avoid but I'll post for reference)
Using Dynamic SQL
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = 'SELECT ID FROM ' + CASE @Var WHEN 'AA' THEN 'Table1'
WHEN 'BB' THEN 'Table2' ELSE 'Table3' END + ' -- WHERE ...'
EXEC(@sql)
Using UNION
SELECT Id
FROM Table1
WHERE @Var='AA'
-- AND ...
UNION ALL
SELECT Id
FROM Table2
WHERE @Var='BB'
-- AND ...
UNION ALL
SELECT Id
FROM Table3
WHERE @Var NOT IN('AA', 'BB')
-- AND ...
Generally speaking, you can't dynamically specify tables in static SQL. You can get the same result a couple of ways, however. The following should work:
Select ID from (
Select ID, WhereParam from Table1 where @Var = 'AA'
union all
Select ID, WhereParam from Table2 where @Var = 'BB'
union all
Select ID, WhereParam from Table3 where @Var not in ('AA','BB'))
where WhereParam = @WhereParam
Using UNION ALL:
SELECT ID FROM Table1
WHERE @Var = 'AA' and Table1.WhereParam = @WhereParam
UNION ALL
SELECT ID FROM Table2
WHERE @Var = 'BB' and Table2.WhereParam = @WhereParam
UNION ALL
SELECT ID FROM Table3
WHERE @Var not in ( 'AA', 'BB' ) and Table3.WhereParam = @WhereParam
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With