0

I've a parameter that is a integer -> @Flag and I've a table with this structure:

ID     Date    Value_A  Value_B Value_C
A   2017-07-14  1          1       1
A   2017-07-13  1          0       1
A   2017-07-12  1          0       1

What I'm trying to get is: - If the parameter @Flag is > 0 then get the rows where Value_A, Value_B or Value_C don't have the same values. In the example above, if the @Flag is 1 then it returns second and third row. - If the parameter @Flag is = 0 then returns all the rows.

I'm trying with this script but I'm getting errors in Sub-Queries:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

DECLARE @Flag INT
SET @Flag = NULL

SELECT *
FROM teste
WHERE Value_A = CASE  
                  WHEN @Flag > 0 THEN 
                   (SELECT Value_B FROM teste WHERE Value_A <> Value_B or Value_A <> Value_C) 
                  ELSE (SELECT Value_A FROM teste) 
                END

How can I do this?

Thanks!

1
  • This answer shows how to use a CASE expression in a JOIN or WHERE. Andy's answer is still a clearer way to express your intent. Commented Jul 14, 2017 at 11:38

2 Answers 2

2

You can't compare single value with set as Value_A = (some set of values).

But in your particular case it is not needed at all, since your query can be simplified as:

SELECT *
FROM teste
where
    (@Flag > 0 and ( Value_A <> Value_B or Value_A <> Value_C))
    or @Flag = 0
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming the values are not the NULL, and you only care about flag being 0 or not zero:

SELECT *
FROM teste
WHERE @Flag = 0 OR
      (Value_A <> Value_B OR Value_A <> Value_C)

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.