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 回答1: Move the condition @tmpValue > 0 to the WHERE clause like so: SELECT * FROM Animal WHERE AniActive = 1 UNION SELECT * FROM Animal WHERE @tmpValue > 0