greener
greener

Reputation: 5069

Statement blocks in SQL SELECT using IF ELSE

I'm trying to return different data depending on a variable in a SELECT. Something like this:

SELECT
   IF @variable = 'YES'
      column1, column2
   ELSE
      column3
FROM TABLE

What is this the proper way to use the IF condition in SQL? Or is there a better alternative to what I'm trying to accomplish?

Upvotes: 0

Views: 4811

Answers (2)

Dan
Dan

Reputation: 547

You can use an IF statement, but you'll need to set up multiple queries. You can use a CASE for selecting one column or another, but not to select one or multiple like in your question.

DECLARE @var INT = 1;

DECLARE @test TABLE (
    Col1 int,
    Col2 int,
    Col3 int
)

INSERT INTO @test VALUES (1,2,3)

IF @var = 1
BEGIN
    SELECT  Col1, Col2
    FROM    @test
END
ELSE
BEGIN
    SELECT  Col3
    FROM    @test
END

Upvotes: 0

Lamak
Lamak

Reputation: 70648

If you want to return a different number of columns, you'll need to use an IF:

IF @variable = 'YES'
BEGIN
    SELECT column1, column2
    FROM YourTable
END
ELSE
BEGIN 
    SELECT column3
    FROM YourTable
END

If you want different data on the same column (assuming the same datatype), you could use a CASE:

SELECT CASE WHEN @variable = 'YES' THEN column1 ELSE Column2 AS Data
FROM YourTable

Upvotes: 5

Related Questions