Paul
Paul

Reputation: 23

SQL Case select

is it possible to select from a different table, based on the results of a case select in mssql?

Upvotes: 2

Views: 587

Answers (4)

HLGEM
HLGEM

Reputation: 96552

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.

Upvotes: 1

KeithS
KeithS

Reputation: 71565

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.

Upvotes: 1

Dustin Laine
Dustin Laine

Reputation: 38503

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)

Upvotes: 4

Stu
Stu

Reputation: 15769

Select
  ConditionalValue = (Case When something Then Table1.Value Else Table2.Value End),
  ...
From
  Table1
  ...
  Table2

For more details, we'll need more details.

Upvotes: 4

Related Questions