简体   繁体   English

动态where子句基于变量

[英]Dynamic where clause based on variable

I am working on a select statement in SQL and am running into issues trying to create a where clause that includes a case statement or an if else statement. 我正在使用SQL中的select语句,并且遇到了尝试创建包含case语句或if else语句的where子句的问题。 I want to select records based on the value of a variable. 我想根据变量的值选择记录。 If the variable is 'True' then only return records from the select statement where a column is null. 如果变量为“True”,则仅返回列为null的select语句中的记录。 If the variable is not 'True' then return all records regardless if that columns is null. 如果变量不是“True”,则返回所有记录,无论该列是否为空。

Any tips on how to do this? 关于如何做到这一点的任何提示?

Below is a simple example of what i am trying to do: 以下是我想要做的一个简单示例:

declare @option1 as varchar(5)

--This can be True or False so to test i just put the Set option below
set @option1 = 'True'

Select a,b,c,d...
from ...
where d = case when @option1 = 'True' then NULL End

This is the part where i do not know what to do. 这是我不知道该怎么做的部分。 I only need to filter out the records if the variable is 'True' so not sure what to put in the else section of the case. 如果变量为“True”,我只需要过滤掉记录,因此不确定在案例的else部分放置什么。

You can't test for d = NULL as your CASE statement does because that will always return false since NULL is not equal to NULL (unless you set ANSI_NULLS to 'off'). 您不能像CASE语句那样测试d = NULL ,因为它总是返回false,因为NULL不等于NULL (除非您将ANSI_NULLS设置为'off')。

The simplest thing to do would be to change the WHERE clause to this: 最简单的方法是将WHERE子句更改为:

WHERE @option1 = 'False' OR d IS NULL

If you prefer to use a CASE statement for some reason, you can write it like this: 如果您出于某种原因更喜欢使用CASE语句,可以这样写:

WHERE 1 = CASE WHEN @option1 = 'False' THEN 1 
               WHEN @option1 = 'True' AND d IS NULL THEN 1 
               ELSE 0 
          END

This: 这个:

UPDATE: PinnyM has straightened me out on this. 更新:PinnyM已经把我拉了出来。 I am leaving my embarrassing logically flawed argument here for the education of the masses. 我在这里为群众的教育留下了令人尴尬的逻辑缺陷。 The solution I propose below after "Try this" is certainly still valid, but PinnyM's solutions is by far more elegant and should be used. 我在“试试这个”之后提出的解决方案当然仍然有效,但PinnyM的解决方案更优雅,应该使用。

WHERE @option1 = 'False' OR d IS NULL WHERE @ option1 ='False'或者d为空

Will always return all the results given his current select statement (assuming @Option1 is simply a flag parameter passed in). 将始终返回给定当前select语句的所有结果(假设@ Option1只是传入的标志参数)。

Try this: 尝试这个:

SELECT a, b, c, d
WHERE 
    -- Returns only rows where d is null (if @Option1 is True)
    (@Option1 = 'True' AND d IS NULL) 
    OR
     -- returns all the rows (if @Option1 is False)
    (@Option1 = 'False')

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

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