-2

Suppose I have a variable @hasAge which can have value either 1 or 0.

I want to write a SELECT query with where clause in which I want to check certain condition if @var is 1 otherwise I don't want to check that condition. Something like this:

SELECT * FROM My_Table mt
WHERE mt.name = 'abcd'
AND
IF(@hasAge)
mt.age > 10 

So I want to compare my.age > 10 only if @hasAge is 1

I dont want to have 2 different select statement like this:

if(@hasAge)
BEGIN
SELECT * FROM My_Table mt
    WHERE mt.name = 'abcd'
    AND
    mt.age > 10
ELSE
BEGIN
SELECT * FROM My_Table mt
    WHERE mt.name = 'abcd'
END
Anirudh Bagri
  • 2,346
  • 1
  • 21
  • 33

1 Answers1

1

Use this:

WHERE mt.name = 'abcd'
AND (@hasAge = 0 OR mt.age > 10)

It means that if @hasAge = 0 then the part after the OR is irrelevant, and if @hasAge <> 0 then the part after the OR is applied.

Peter B
  • 22,460
  • 5
  • 32
  • 69