Sql查询帮助。如何在where子句中正确获取项目

时间:2013-03-07 18:13:28

标签: sql-server sql-server-2008

我创建了这个删节的SQL查询。它需要一个只有2个字符(“GR”,“PH”......等)的级别代码,我需要更改查询以允许在一个实例中返回多个项目。

这是代码

    DECLARE @ALEVL_CODE varchar(5), @test varchar(100)
    SET @ALEVL_CODE = 'GR'
    SET @test = @ALEVL_CODE + ',' + 'PH'

-
                    select ALEVL_CODE  from PMP_Admissions_Letter_Data AD
                    INNER JOIN      PMP_LM_Review LMR
    ON              LMR.PMP_Letter_Data_ID = AD.PMP_Admissions_Letter_Data_ID
    WHERE           LMR.ToPrinter = 1 AND
                    LMR.Extracted = 0 AND 
                    AD.ALEVL_CODE = @ALEVL_CODE                 
                    AND
                    AD.DSCN_MAX_CODE = 'PA'

我遇到的问题是在where子句中使用行AD.ALEVL_CODE=@ALEVL_CODE。我希望@ALEVL_CODE GR GR然后PH@ALEVL_CODE只做{{1}}。这有意义吗?一些帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

    AND (AD.ALEVL_CODE = @ALEVL_CODE
         OR (@ALEVL_CODE='GR' AND AD.ALEVL_CODE = 'PH'))

简化的替代方案。

答案 1 :(得分:1)

            select ALEVL_CODE  from PMP_Admissions_Letter_Data AD
            INNER JOIN      PMP_LM_Review LMR
ON              LMR.PMP_Letter_Data_ID = AD.PMP_Admissions_Letter_Data_ID
WHERE           LMR.ToPrinter = 1 AND
            LMR.Extracted = 0 AND 
            ((@ALEVL_CODE = 'GR' AND AD.ALEVL_CODE in ('GR', 'PH')) 
                OR (@ALEVL_CODE <> 'GR' AND AD.ALEVL_CODE = @ALEVL_CODE))                 
            AND
            AD.DSCN_MAX_CODE = 'PA'

答案 2 :(得分:0)

and case when (@ALEVL_CODE = 'GR') then AD.ALEVL_CODE in ('GR', 'PH') 
         else AD.ALEVL_CODE = @ALEVL_CODE
    end