0

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.