SQL Server存储过程

时间:2011-08-18 14:01:24

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

我希望它计算然后if @intcount > 0它应该显示数据或者没有找到数据,但是当我执行它时,我发现'没有找到数据',我做错了什么?

@FiscalYear int,
@SchoolID int,
@Status int

AS
BEGIN

SET NOCOUNT ON;

declare @sqlstr varchar(2000)
declare @intCount int
set @intCount = 0

set @sqlstr = 'Select @intCount = Count(*)
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID 
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

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

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else 
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'


 If (@intCount > 0)
 BEGIN
 set @sqlstr=   'Select SchoolName as School, 
 (Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''    
  ELSE ''Not Uploaded'' END) AS Status,
  COUNT(Attachment.PrivateSchoolID) AS [Count] 
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID 
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'



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

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else 
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

    SET @sqlstr = @sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
    SET @sqlstr = @sqlstr + ' Order By SchoolName'
EXEC(@sqlstr)
 END
 ELSE
 Select 'No Data Found' as 'FileUpload'
 END

3 个答案:

答案 0 :(得分:3)

你需要:

EXEC sp_executesql @sqlstr, N'@intCount INT OUTPUT', @intCount = @intCount OUTPUT;

IF (@intCount > 0)
BEGIN
    ....
END

您还需要制作@sqlstr NVARCHAR(2000)并将其设置为N'SELECT ...'而不是'SELECT ...' - 前导N可能非常重要。

答案 1 :(得分:1)

问题是:

declare @intCount int
set @intCount = 0
...
<a bunch of code where @intcount doesn't change>
If (@intCount > 0)

它总是为0。

答案 2 :(得分:0)

您的问题属于范围之一。 EXEC(@sqlstr)命令无权访问存储过程中的@intcount变量。我敢打赌,如果你在查询窗口中运行此代码,它会告诉你声明@intcount。

听YUCK并重写它以避免动态SQL,然后你的SELECT将能够设置@intcount变量。