简体   繁体   English

Sql Server 联合与 If 条件

[英]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.当我这样使用时,它会因为 if 条件而出错。 I have to use UNION because of our structure.由于我们的结构,我必须使用 UNION。

How can I use it with if condition?如何在 if 条件下使用它?

Thanks,谢谢,
John约翰

Move the condition @tmpValue > 0 to the WHERE clause like so:将条件@tmpValue > 0移动到WHERE子句,如下所示:

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

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

Best way to put condition in Query is CASE statement .在 Query 中放置条件的最佳方法是 CASE 语句。 you can put any number of condition in query .您可以在 query 中放置任意数量的条件。 CASE statement is used to put conditional filters in Query . CASE 语句用于在 Query 中放置条件过滤器。

For EX.对于 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 .您的情况并不复杂,但对于更复杂的情况,您可以在 Query 中使用嵌套的 CASE 语句。

Here is way to do it that simplifies the code by getting rid of the UNION altogether.这是通过完全摆脱 UNION 来简化代码的方法。 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.如果 select 执行表扫描,这也会表现得更好,因为它只会扫描一次而不是(可能)两次。

DECLARE @tmpValue

SET @tmpValue = 0 -- it will be change

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM