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
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,
You should be able to do something similar in other versions of SQL.