简体   繁体   English

SQL Case NOT NULL作为值

[英]SQL Case NOT NULL as value

I'm trying to return NOT NULL and NULL as the result of a CASE statement but I can't find the right way to do it 我正在尝试通过CASE语句返回NOT NULL和NULL,但找不到正确的方法

What I have below is incorrect and underlines the NOT keyword 我下面的内容不正确,并强调了NOT关键字

SELECT  ROW_NUMBER() OVER ( ORDER BY d.cnumber DESC) AS RowNum,
    d.cnumber,
    d.firstname,
    d.lastname,
    d.current_email,
    d.updated_email,
    d.optedin,
    d.activated             
FROM    
    Customer d 
WHERE (d.optedin = 
           CASE WHEN @query = 'UNSUBMITTED' OR @query = 'SUBMITTED' 
                    THEN d.optedin
                WHEN @query = 'OPTEDIN' 
                    THEN 1
                ELSE 0 END) AND
      (d.activated =
           CASE WHEN @query = 'OPTEDIN' OR @query = 'OPTEDOUT' 
                    THEN d.activated 
                WHEN @query = 'UNSUBMITTED' 
                    THEN NULL 
                ELSE NOT NULL END)

activated is a nullable datetime field. activated是一个可为空的日期时间字段。 @query is a varchar parameter @query是varchar参数

Using a case in a where clause is usually an indication you've taken the wrong path. 通常在where子句中使用case表示您走错了路。 I believe that you'll find you can solve this with more standard logic: 我相信您会发现您可以使用更多标准逻辑来解决此问题:

WHERE (@query in ( 'UNSUBMITTED', 'SUBMITTED') 
         OR (@query = 'OPTEDIN' AND d.optedin = 1)
         OR d.optedin = 0)
       AND
      (@query in ('OPTEDIN', 'OPTEDOUT')
         OR (@query = 'UNSUBMITTED' AND d.activated IS NULL)
         OR  d.activated IS NOT NULL)

I suggest you modify the condition for d.activated to this: 我建议您将d.activated的条件修改为此:

AND (@query = 'UNSUBMITTED' AND d.activated IS NULL OR @query <> 'UNSUBMITTED' AND d.activated IS NOT NULL)

Please note that you do not need to specifically test for this condition: 请注意,您不需要专门测试这种情况:

CASE WHEN @query = 'OPTEDIN' OR @query = 'OPTEDOUT' 
                THEN d.activated 

As it will be covered by OR d.activated IS NOT NULL in the condition that I have proposed 因为它将由OR d.activated IS NOT NULL ,所以在我提出的条件下, OR d.activated IS NOT NULL

BTW, for d.optedin you can use the similar: 顺便说一句,对于d.optedin,您可以使用类似的命令:

(@query = 'OPTEDIN' AND d.optedin = 1 OR @query <> 'OPTEDIN' AND d.optedin = 0)

This: 这个:

ELSE NOT NULL 

is too vague. 太模糊了。 SQL Server does not know what to return. SQL Server不知道返回什么。 You have to specify a value that is the same datatype as d.activated. 您必须指定与d.activated相同的数据类型的值。

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

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