Where子句中的SQL条件语句

时间:2013-05-13 20:56:14

标签: sql-server-2008 where-clause conditional-statements

我想在SQL中编写以下IF语句。大多数where子句都是构造的,但这是我正在努力解决的语句的条件:

if @StuYear = 11 then

AND (@TeachingGroup = 'Select All')
AND ([DataCollection] = @DataCollection)
AND ([Name] = @SubjectName) 
AND (@Subgroup='Select All') 
AND '' = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END 
AND Result Not Like '[ABU]%' AND Result <> ''

else if @StuYear = 10 then 

AND @TeachingGroup Not Like 'Select All' 
AND ([DataCollection] = @DataCollection) 
AND ([Name] = @SubjectName) 
AND ([TeachingGroup] = @TeachingGroup)  
AND @Subgroup='Select All' 
AND '' = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END 
AND Result Not Like '[ABC]%' AND Result <> ''

end if

2 个答案:

答案 0 :(得分:1)

只需将if替换为where,将else if替换为or,并将其他条件置于paranthesis中:

...
where (@StuYear = 11 
AND (@TeachingGroup = 'Select All')
AND ([DataCollection] = @DataCollection)
AND ([Name] = @SubjectName) 
AND (@Subgroup='Select All') 
AND '' = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END 
AND Result Not Like  'A*' 
AND Result Not Like 'A' 
AND Result Not Like 'B' 
AND Result Not Like 'U' 
AND Result Not Like '' )

OR (@StuYear = 10 
AND @TeachingGroup Not Like 'Select All' 
AND ([DataCollection] = @DataCollection) 
AND ([Name] = @SubjectName) 
AND ([TeachingGroup] = @TeachingGroup)  
AND @Subgroup='Select All' 
AND '' = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END 
AND Result  Not Like  'A*' 
AND Result  Not Like  'A' 
AND Result Not Like 'B' 
AND Result  Not Like  'C' 
AND Result  Not Like '')

答案 1 :(得分:0)

蒂姆的回答帮助我指明了正确的方向。但是,我最终通过在where子句中应用year条件而不是在它们周围敲击来解决这个问题:

where 
    (@StuYear = [stuyear]
    AND @TeachingGroup = 'Select All'
    AND [DataCollection] = @DataCollection
    AND [Name] = @SubjectName
    AND @Subgroup='Select All'
    AND '' = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
    AND ((Result Not Like '[ABU]%' and result not like '' and stuyear='11')
            or(Result Not Like '[ABC]%' and result not like '' and stuyear='10')
            or(Result Not Like '[ABCD]%' and stuyear='9'))
    AND Result <> '')
OR 
    (@StuYear = [stuyear]
        AND @TeachingGroup Not Like 'Select All'
        AND [DataCollection] = @DataCollection
        AND [Name] = @SubjectName
        AND [TeachingGroup] = @TeachingGroup
        AND @Subgroup='Select All'
        AND '' = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
        AND ((Result Not Like '[ABU]%' and result not like '' and stuyear='11')
                or(Result Not Like '[ABC]%' and result not like '' and stuyear='10')
                or(Result Not Like '[ABCD]%' and stuyear='9'))
        AND Result <> '')