SQL嵌套CASE - 快捷逻辑?

时间:2013-04-23 14:54:17

标签: sql logic case shortcut

我试图摆脱所有动态SQL代码。这个存储过程似乎需要一些带有WHERE子句的嵌套CASE语句。这是按预期工作的。但是,我担心表现。如果父CASE语句不为真,是否会执行嵌套(GuarantorNumber not in(select ...))语句?

WHERE 1 = CASE WHEN ( @method='ADDED_RECORDS' ) THEN
      CASE WHEN 
        ( pt.[GuarantorNumber] not in (select cpg.GuarantorNumber from [CorepointProtectedGuarantor] cpg) ) THEN
          1
          ELSE 0 END -- NEW_RECORDS

       WHEN ( @method='DELETED_RECORDS' ) THEN
      CASE WHEN 
        ( pt.[GuarantorNumber] not in (select mpg.GuarantorNumber from [MeditechProtectedGuarantor] mpg) ) THEN
          1
          ELSE 0 END -- DELETED_RECORDS

       WHEN ( @method='UPDATED_RECORDS' ) THEN
      CASE WHEN 
        ( pt.[GuarantorNumber] in 
            (SELECT mpg.GuarantorNumber FROM 
                  [MeditechProtectedGuarantor] mpg, 
                  [CorepointProtectedGuarantor] cpg 
            WHERE 
                  mpg.GuarantorNumber = cpg.GuarantorNumber and
                  (mpg.[LastName] <> cpg.[LastName] OR 
                        mpg.[FirstName] <> cpg.[FirstName] OR 
                        mpg.[MiddleName] <> cpg.[MiddleName] OR 
                        mpg.[Address] <> cpg.[Address] OR 
                        mpg.[AddressLine2] <> cpg.[AddressLine2] OR 
                        mpg.[City] <> cpg.[City] OR 
                        mpg.[State] <> cpg.[State] OR 
                        mpg.[ZIP] <> cpg.[ZIP] OR 
                        mpg.[Phone] <> cpg.[Phone])

            ) -- end of SELECT clause
            ) -- end of WHEN clause 
            THEN
          1
          ELSE 0 END -- UPDATED_RECORDS

2 个答案:

答案 0 :(得分:0)

搜索CASE表达式:

  • 返回第一个求值为TRUE的input_expression = when_expression的result_expression。

在你的情况下,如果@ method ='ADDED_RECORDS'和@ method ='DELETED_RECORDS'为假,则下一个语句将被执行WHEN(@ method ='UPDATED_RECORDS')在SQLServer2008中通过按Cntl + L来分析此行为

答案 1 :(得分:0)

Declare @query nvarchar(max) 

Declare @selectoneCount int

Declare @Temp int

SET @Temp =1

Declare @val nvarchar(max)

SET @val =''

select 
       @query = case @Temp

       when 1 

       then       
          case @val

          when 'NULL'

          then
            ('Select Diameter from BallsProbes where Remark =2') 

          else
            ('Select Diameter from BallsProbes where Remark =3')   
            END 
       when 2 
       then ('Select Diameter from BallsProbes where Remark =6')
       end

EXEC(@query)