Sql Server union with If condition

♀尐吖头ヾ 提交于 2021-02-18 09:33:52

问题


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 AND Active = 0



回答2:


You can add your condition to the query like this. the section part of the union will simply return no results if your test condition is false:

DECLARE @tmpValue

SET @tmpValue = 0 -- it will be change 

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



回答3:


Best way to put condition in Query is CASE statement . you can put any number of condition in query . CASE statement is used to put conditional filters in Query .

For EX.

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

SELECT * FROM Animal WHERE AniActive = 1
UNION
SELECT * FROM Animal 
WHERE 
1 = CASE WHEN @tmpValue  = 0 THEN 0 ELSE Active = 1 END

your situation is not to complex but for more complex condition you can use nested CASE statement in Query .




回答4:


Here is way to do it that simplifies the code by getting rid of the UNION altogether. I always prefer a simpler solution where possible. This will also perform better if the select does a table scan, since it will only scan it once rather than (potentially) twice.

DECLARE @tmpValue

SET @tmpValue = 0 -- it will be change

SELECT * FROM Animal WHERE AniActive = 1 OR @tmpValue > 0


来源:https://stackoverflow.com/questions/13176954/sql-server-union-with-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!