Stored Procedure with dynamic SQL returns wrong data
For the fiscal year parameter I have 2010, 2011 and 2012 as an option but no matter what year I select the "submitted On" column still shows 2011 dates. I want for example if I select 2010, only data submitted on 2010 should show and likewise for all the years. Any help?
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 + ' A开发者_高级运维ND (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
There is no need at all for dynamic sql here.
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
精彩评论