Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Select from Different Table based on a CASE value

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
like image 584
SF Developer Avatar asked Nov 18 '13 18:11

SF Developer


3 Answers

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 ...
like image 94
T I Avatar answered Nov 02 '22 16:11

T I


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
like image 40
Allan Avatar answered Nov 02 '22 17:11

Allan


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
like image 33
HABO Avatar answered Nov 02 '22 15:11

HABO