简体   繁体   English

sql server选择大小写在哪里

[英]sql server select where case IN

Please help with syntax, i need where IN clause only when parameter = 1 otherwise all records 请帮助语法,我仅在参数= 1时才需要IN子句,否则所有记录

not working 不工作

SELECT * FROM T 
    WHERE T.C = 'AAA' 
    AND CASE WHEN @Param = 1 THEN T.ID IN ('1','2','3') END - this condition only needed when @param = 1

Im try below, but how get all records? 我在下面尝试,但是如何获取所有记录?

   AND T.ID IN CASE WHEN @Param = 1 THEN ('1','2','3') ELSE -all rows- END

Don't use CASE for this. 不要为此使用CASE

Rewrite your SQL like this: 像这样重写您的SQL:

WHERE
    T.C = 'AAA'
AND (
    (@Param = 1 AND T.ID IN ('1', '2', '3'))
    OR
    (@Param <> 1)
    )

Remove whitespace as needed when you understand how/why it works. 了解空格的工作原理后,请根据需要删除空格。

It can even be shortened down if we change the order of the OR part (not necessary really but easier to understand for us humans then): 如果我们更改OR部分的顺序,它甚至可以缩短(不是必须的,但是对于我们人类来说则更容易理解):

WHERE
    T.C = 'AAA'
AND (
    @Param <> 1
    OR
    T.ID IN ('1', '2', '3')
    )

If @Param is not different from 1, it has to be 1, so then you don't need to explicitly check this in the other branch. 如果@Param是没有差异的1,它必须是1,那么你就不需要在另一个分支中明确检查。

Thus the best way to do this is this: 因此,执行此操作的最佳方法是:

WHERE
    T.C = 'AAA'
AND (@Param <> 1 OR T.ID IN ('1', '2', '3'))

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

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