Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server union with If condition

I have a query like:

DECLARE @tmpValue
SET @tmpValue = 0 -- it will be change 

SELECT * FROM Animal WHERE AniActive = 1
UNION 
IF @tmpValue > 0 
SELECT * FROM Animal WHERE.Active = 0

When I use like this it is giving error because of if condition. I have to use UNION because of our structure.

How can I use it with if condition?

Thanks,
John

like image 694
John Avatar asked Nov 01 '12 12:11

John


Video Answer


1 Answers

Move the condition @tmpValue > 0 to the WHERE clause like so:

SELECT * FROM Animal WHERE AniActive = 1
UNION
SELECT * FROM Animal WHERE @tmpValue > 0 AND Active = 0
like image 150
Mahmoud Gamal Avatar answered Oct 08 '22 18:10

Mahmoud Gamal