带 OR 的 where 子句中的 Case 语句

发布于 2024-07-30 11:24:10 字数 589 浏览 5 评论 0原文

提前道歉,因为我觉得我可能忘记/遗漏了一些明显的事情。 开始; 我在 WHERE 子句中使用 case 语句,以下工作正常:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol =  
(
CASE WHEN (@Year = 0 AND @Period = 0) THEN
@SomeVal
     WHEN...
...
     ELSE
@SomeVal
END 

我的“问题”是我想向我的 ELSE 块添加一个附加的 OR 子句..像这样:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol =  
(
CASE WHEN (@Year = 0 AND @Period = 0) THEN
@SomeVal
     WHEN...
...
     ELSE
@SomeVal OR @SomeVal - 1
END 

当然,这会引发此错误: 关键字“OR”附近的语法不正确。 在 ELSE 语句中

因此我的问题...我可以用来完成此操作的正确/替代逻辑是什么?
先感谢您

Apologies in advance since I feel like I'm probably forgetting/missing something obvious on this one. Here goes; I'm using a case statement in my WHERE clause, the below works fine:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol =  
(
CASE WHEN (@Year = 0 AND @Period = 0) THEN
@SomeVal
     WHEN...
...
     ELSE
@SomeVal
END 

My "issue" is that I want to add an additional OR clause to my ELSE block..something like this:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol =  
(
CASE WHEN (@Year = 0 AND @Period = 0) THEN
@SomeVal
     WHEN...
...
     ELSE
@SomeVal OR @SomeVal - 1
END 

Naturally, this throws this error:
Incorrect syntax near the keyword 'OR'. within the ELSE statement

Hence my question...what is the correct/alternate logic I can use to accomplish this?
Thank you in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生路 2024-08-06 11:24:10

CASE 是一个返回一个值的表达式。 您可以在两个表达式之间执行 OR 操作,而不是针对单个 CASE 表达式进行测试,唯一的区别是 else 子句。 (使用 IN 作为编写 SomeOtherCol = ... OR SomeOtherCol = 的快捷方式)您可以这样做:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol in   
    (CASE WHEN (@Year = 0 AND @Period = 0) THEN
        @SomeVal
        CASE WHEN...
            ...
        CASE ELSE
        @SomeVal END,
    CASE WHEN (@Year = 0 AND @Period = 0) THEN
        @SomeVal
        CASE WHEN...
            ...
        CASE ELSE
        @SomeVal - 1 END)

我的猜测是这比您需要的逻辑更多,并且如果具体情况了解您的情况后,可以写出更简单、更清晰的其他声明。

CASE is an expression that returns one value. Instead of testing against the single CASE expresssion, you could do an OR between two, that only difference is the else clause. (Using IN as a shortcut for writing SomeOtherCol = ... OR SomeOtherCol =) You could do:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol in   
    (CASE WHEN (@Year = 0 AND @Period = 0) THEN
        @SomeVal
        CASE WHEN...
            ...
        CASE ELSE
        @SomeVal END,
    CASE WHEN (@Year = 0 AND @Period = 0) THEN
        @SomeVal
        CASE WHEN...
            ...
        CASE ELSE
        @SomeVal - 1 END)

My guess is this has more logic than you need, and if the specifics of your situation were known a much simpler and clearer else statement could be written.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文