Where子句内的SQL Server Case语句生成错误

ssm49v7z  于 2022-12-03  发布在  SQL Server
关注(0)|答案(2)|浏览(170)

正在使用以下SQL,但where子句内的case语句出错。

create procedure MyProcedure 
    @ApprovalFilter as nvarchar(50), 
    @BothPendingAndApproved as nvarchar(50)

Select 
    * 
from 
    myTable
Where
    data = "A"
    and 
        case @BothPendingAndApproved 
            when 'Both' then ApprovalStatus <> 'Rejected'
            when 'Specific' then ApprovalStatus like @ApprovalFilter
        end
    and 
    Data2="B"

End

为什么这部分会失败?

case @BothPendingAndApproved 
        when 'Both' then ApprovalStatus <> 'Rejected'
        when 'Specific' then ApprovalStatus like @ApprovalFilter
    end
z3yyvxxp

z3yyvxxp1#

CASE不是语句而是表达式,它返回标量值。可以重构CASE表达式以用作 predicate :

Select 
    * 
from 
    myTable
Where
    data = 'A'
    and 
        case  
            when @BothPendingAndApproved = 'Both' and ApprovalStatus <> 'Rejected' THEN 1
            when @BothPendingAndApproved = 'Specific' and ApprovalStatus like @ApprovalFilter THEN 1
        end = 1
    and 
    Data2='B'

恕我直言,使用OR条件会更清楚一些:

create procedure MyProcedure 
    @ApprovalFilter as nvarchar(50), 
    @BothPendingAndApproved as nvarchar(50)
AS
Select 
    * 
from 
    myTable
Where
    data = 'A'
    and (
            (@BothPendingAndApproved = 'Both' and ApprovalStatus <> 'Rejected')
            OR (@BothPendingAndApproved = 'Specific' and ApprovalStatus like @ApprovalFilter)
        )
    and 
    Data2='B'
    OPTION(RECOMPILE); --consider this option to optimize the query

请注意,为实现ANSI兼容性而对字符文字使用单引号,并使用SQL Server功能(如筛选索引、索引视图等)。

ee7vknir

ee7vknir2#

正如注解中所解释的,CASE并不是这样工作的,你可以使用“简单的”AND/OR条件:

Where
   data = "A"
   and 
   (
     (@BothPendingAndApproved  = 'Both' AND ApprovalStatus <> 'Rejected')
     OR 
     (@BothPendingAndApproved = 'Specific' AND ApprovalStatus like @ApprovalFilter)
   )
   and 
   Data2="B"

相关问题