MS SQL存储过程根据空白参数返回意外结果

时间:2013-06-18 09:16:23

标签: sql-server variables stored-procedures parameters

我将参数从asp.net webform传递给存储过程。

但是,对于一个特定的参数组合,单个参数似乎被忽略。

我传递的导致问题的参数如下:

EXEC    @return_value = [dbo].[spProgressCohorts]
    @StuYear = N'10',
    @DataCollection = N'March 2013 Teacher Assessments',
    @SubjectName = N'English',
    @TeachingGroup = N'Select All',
    @Subgroup = N'Select All',
    @KS2 = '',
    @Result = ''

当我使用这些参数运行存储过程时,结果将返回,就好像忽略@Result变量一样。

存储过程返回的结果(包括ks2en和结果列以供参考):

surname     forename    ks2en   result
El Hajj     Zeinab              D
Grzelak     Marlena             F+
Sage        Nigel       

然而,当我运行以下查询时,我得到Nigel Sage的记录(正如预期的那样,这是存储过程应该返回的记录):

select surname, forename, ks2en, result 
    from student join subject on subject.upn=student.upn 
where datacollection='March 2013 Teacher Assessments' and stuyear='10' and name='english' and result='' and ks2en=''

我的存储过程非常庞大,所以我只需要包含特定于上述参数的代码:

ALTER PROCEDURE [dbo].[spProgressCohorts]
    @StuYear varchar(2),  
    @DataCollection varchar(100), 
    @SubjectName varchar(100), 
    @TeachingGroup varchar(30), 
    @Subgroup varchar(10), 
    @Result varchar(4), 
    @KS2 varchar(4)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
 --interfering with SELECT statements.
SET NOCOUNT ON;

SELECT Forename + ' ' + Surname

FROM student
   JOIN subject
     ON subject.upn = student.upn
WHERE 
    (@StuYear = [stuyear]
    AND @TeachingGroup = 'Select All'
    AND [DataCollection] = @DataCollection
    AND [Name] = @SubjectName
    AND @Subgroup='Select All'
    AND @KS2 = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
    AND [Result] like @Result + '%')
OR 
    (@StuYear = [stuyear]
        AND @TeachingGroup Not Like 'Select All'
        AND [DataCollection] = @DataCollection
        AND [Name] = @SubjectName
        AND [TeachingGroup] = @TeachingGroup
        AND @Subgroup='Select All'
        AND @KS2 = CASE @subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
        AND [Result] like @Result + '%')

ORDER BY surname, forename

1 个答案:

答案 0 :(得分:1)

这个怎么样?

...
AND [Result] LIKE CASE @Result WHEN '' THEN '' ELSE @Result + '%' END)