在WHERE子句中使用CASE

时间:2011-08-09 23:31:01

标签: sql sql-server

以下是代码:

CREATE PROCEDURE [dbo].[PR_CDMS_ADMIN_GET_SECURITY_INFO] (    
 DECLARE @chvMajorCatgry varchar(50) 
 DECLARE @chvMinorCatgry varchar(50)   

)    
AS        

if (@chvMajorCatgry = 'yyy')
    begin
        select caf.ACTN_FACT_SID            
        from CDMS_ACTN_FACT caf     
        where caf.ACTN_SID in (select ACTN_SID from CDMS_ACTN where ACTN_CATGRY_CD = 'yyy') 
        print @chvMajorCatgry   
    end
    print @chvMajorCatgry
else if (@chvMajorCatgry = 'zzz')
    begin 
        select  caf.ACTN_FACT_SID           
        from CDMS_ACTN_FACT caf     
        where caf.ACTN_SID = (select ACTN_SID from CDMS_ACTN where ACTN_CATGRY_CD = 'zzz' and ACTN_CD = @chvMinorCatgry)        
    end

如何处理这个以获得一个select语句?

2 个答案:

答案 0 :(得分:2)

Bleh,这很粗糙。试试这个:

    select  caf.ACTN_FACT_SID           
    from CDMS_ACTN_FACT caf     
    where caf.ACTN_SID IN (
               select ACTN_SID 
               from CDMS_ACTN 
               where ( 
                       @chvMinorCatgry = 'zzz' 
                       AND ACTN_CATGRY_CD = 'Attribute' 
                       AND ACTN_CD = @chvMinorCatgry)
                     )
               OR    (
                       @chvMinorCatgry = 'yyy' 
                       AND ACTN_CATGRY_CD = 'Account'
                     )
             )

答案 1 :(得分:0)

请在下面找到我的建议。您可能需要在子查询中更改case语句末尾的通配符,具体取决于ACTN_CD列的数据类型。

CREATE PROCEDURE [dbo].[PR_CDMS_ADMIN_GET_SECURITY_INFO] (    
  @chvMajorCatgry varchar(50),
 @chvMinorCatgry varchar(50)   
 --SET @chvMajorCatgry = 'Account'
)    
AS      

select caf.ACTN_FACT_SID            
from CDMS_ACTN_FACT caf     
where caf.ACTN_SID in (
                       select ACTN_SID 
                       from CDMS_ACTN 
                       where ACTN_CATGRY_CD = @chvMajorCatgry
                       and ACTN_CD like case @chvmajorcatgry when 'Attribute' then @chvMinorCatgry else '%' end)