SQL Case select
is it possible to select from a different table, based on the results of a case select in 开发者_StackOverflow中文版mssql?
Select
ConditionalValue = (Case When something Then Table1.Value Else Table2.Value End),
...
From
Table1
...
Table2
For more details, we'll need more details.
You can build dynamic SQL and then execute it.
DECLARE @SQL nvarchar(1000)
SET @SQL = 'SELECT * FROM '
CASE Condition
WHEN 1 THEN @SQL = @SQL + 'TABLE '
ELSE @SQL = @SQL + 'TABLE1 '
END
EXEC(@SQL)
Well, if the tables have some 1-to-1 relationship, you can join them, then return a column from A or from B depending on a case operator for the column. Barring that, you can use procedural code (TransactSQL) to test the condition that determines the table from which to select, and call one select statement or the other that return identical columns, but each is pointed to a single table. If the tables have similar schemas and you're querying them from a program, you can manipulate the string representation of the command based on the condition you wish to check. Lastly, you can UNION two queries, each pointing at a different table, with a WHERE clause on each subquery that evaluates the condition and does not return any rows if false.
THe IF statment controls flow not CASE. If you want to select values from one of two differnttables that are both in the joins in the query, CASE is appropriate, otherwise use IF.
精彩评论