使用动态SQL的存储过程返回错误的数据

时间:2011-09-01 16:02:18

标签: sql sql-server sql-server-2005

对于会计年度参数,我将2010,2011和2012作为选项,但无论在哪一年,我选择“提交时间”列仍显示2011年日期。我希望例如,如果我选择2010年,则仅显示2010年提交的数据,并且同样适用于所有年份。有什么帮助吗?

  set @sqlstr = '
  Select 
    [SchoolName] As [School Name],
    Status= CASE  WHEN PS.PrivateSchoolID = Ed.PrivateSchoolID THEN ''Submitted'' 
         ELSE ''Not Submitted''END,
    [Submitted By]= CASE WHEN PS.PrivateSchoolID = Ed.PrivateSchoolID 
             THEN [FirstName] + '' '' + [LastName] ELSE NULL END,
    [Submitted On]= CASE WHEN PS.PrivateSchoolID = Ed.PrivateSchoolID 
               THEN Convert( Varchar(10), Ed.CreatedDate, 101 ) ELSE NULL END
   From EnrollmentDateSchool Ed Right Outer Join 
    (select FP.FiscalYear, PrivateSchool.* from PrivateSchool
        INNER JOIN FiscalYearPrivateSchool FP 
                ON PrivateSchool.PrivateSchoolID = FP.PrivateSchoolID) PS 
          ON Ed.PrivateSchoolID = PS.PrivateSchoolID Left Outer Join 
    Finance.dbo.Person P ON Ed.CreatedBy = P.PersonID
  Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PS.IsActive = 1)' 


IF (@SchoolID != -1)
    set @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

IF (@Status = -1)
    set @sqlstr = @sqlstr + ' AND (PS.PrivateSchoolID = PS.PrivateSchoolID' + ')'
ELSE IF (@Status = 1)
    set @sqlstr = @sqlstr + ' AND (PS.PrivateSchoolID = Ed.PrivateSchoolID' + ')'
ELSE 
    set @sqlstr = @sqlstr + 'AND (Ed.PrivateSchoolID is null' + ')'

    SET @sqlstr = @sqlstr + 'ORDER BY SchoolName'
 EXEC(@sqlstr)
 END

1 个答案:

答案 0 :(得分:6)

这里根本不需要动态sql。

SELECT
   ...
FROM ...
WHERE FiscalYear=@FiscalYear AND PS.IsActive=1
AND (@SchoolID = -1 OR SchoolID=@SchoolID)
AND ( (@Status = -1) 
      OR (@Status=1 AND PS.PrivateSchoolID = Ed.PrivateSchoolID) 
      OR (Ed.PrivateSchoolID is null) )
ORDER BY SchoolName