tags:

views:

82

answers:

4

Is there a clean way in sql to create a select statement based on a case statement?

I'm looking for the basic logic to be something like

   CASE @tableToUse
           WHEN 'Table1' SELECT * FROM Table1 
           WHEN 'Table2' SELECT * FROM table2 
           DEFAULT 'Table3' SELECT * FROM table3
   END CASE
+2  A: 

In T-Sql (MS SQL Server) you can dynamically compose your SQL statement and then use the sp_executesql method to execute it. Based on your case statement you can build a SELECT statement using a variable and then use sp_executesql to run it. The one thing to be aware of is that you need to make sure you clean any input you get from users if you are using text directly from users to prevent SQL injection attacks.

For example,

DECLARE @sql NVARCHAR(200)

SELECT @sql = CASE @tableToUse
    WHEN 'Table1' THEN 'SELECT * FROM Table1'
    WHEN 'Table2' THEN 'SELECT * FROM Table2'
    ELSE 'Table3' THEN 'SELECT * FROM Table2'
    END

EXECUTE sp_executesql @sql

You should be able to do something similar in other versions of SQL.

TLiebe
Of course this is the required reading if you plan to use dynamic SQLhttp://www.sommarskog.se/dynamic_sql.html
HLGEM
A: 

Why not just join to the testTable on username?

HLGEM
I see that would make sense for the example I gave above. But just for educational purposes I want to know how to execute a select based on the results from a case statement.
Ben
I could only answer the question you asked. Since you have changed the question, go with JohnFx or TLiebe's answer.
HLGEM
+3  A: 

Sorry, Case statements in tSQL (which I assume you are asking about) are for evaluating expressions only and can't be used for control flow.

You are pretty much stuck with IF..THEN

IF (@Something='Table1')
    SELECT Field1 from table1
ELSE
   IF (@Something='Table2')
        SELECT Field1 from table2
   ELSE
        SELECT Field1 From table3
JohnFx
@downvoter: Don't shoot the messenger. I didn't write the tSQL language.
JohnFx
+ 1 This is the correct answer, if OP wants static SQL and if OP is using SQL Server (T-SQL). Static SQL does have some advantages versus using dynamic SQL.
Shannon Severance
A: 

You can do this ! only that you cannot do a "select *" as that might return more than one value that shoot an error even if that has to be a table with a single column

SELECT   columnName = CASE WHEN 'foo' THEN select <Column_Name> from tableName where columnName = 'this'  
                           WHEN 'bar' THEN select <Column_Name>  from tableName where columnName = 'that' 
END 
FROM tableName 
Baaju