-1

I would like to write the following IF statement in SQL. Most of the where clause is constructed, but it's the condition around the statement that I'm struggling with:

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
4

2 回答 2

1

只需ifwhereelse if替换并or在括号中包围其他条件:

...
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 '')
于 2013-05-13T21:01:27.930 回答
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 <> '') 
于 2013-05-15T13:26:21.690 回答