select top @varible

        在MS SQL Server 2K5中写的一个存储过程如下:
CREATE PROCEDURE [dbo].[GetRecentNews]
     @SchoolID int,
     @NewsType int,
     @PageSize tinyint,
     @Page int
AS
 --分页
 if(NewsType=0)
     SELECT TOP @PageSize ID,Title,UpdateTime FROM News WHERE  SchoolID=@SchoolID AND ID NOT IN
  (SELECT TOP @PageSize*(@Page-1) ID FROM News WHERE SchoolID=@SchoolID  ORDER BY UpdateTime DESC)  ORDER BY UpdateTime DESC  
 else
     SELECT TOP @PageSize ID,Title,UpdateTime FROM News WHERE  SchoolID=@SchoolID AND NewsType=@NewsType AND ID NOT IN
  (SELECT TOP @PageSize*(@Page-1) ID FROM News WHERE SchoolID=@SchoolID AND NewsType=@NewsType ORDER BY UpdateTime DESC)  ORDER BY UpdateTime DESC

   RETURN
GO


      在SQL Server 2K5中没有问题,但到了Sql Server 2K中,却报错:
服务器: 消息 170,级别 15,状态 1,过程 GetRecentNews,行 9
第 9 行: '@PageSize' 附近有语法错误。
服务器: 消息 170,级别 15,状态 1,过程 GetRecentNews,行 10
第 10 行: '@PageSize' 附近有语法错误。
服务器: 消息 170,级别 15,状态 1,过程 GetRecentNews,行 13
第 13 行: '@PageSize' 附近有语法错误。

     晕!Sql Server 2K中写法如下:
CREATE PROCEDURE [dbo].[GetRecentNews]
 @SchoolID int,
 @NewsType int,
 @PageSize int,
 @Page int
AS
 --分页
 declare @current int
 set @current= @PageSize*(@Page-1)
 if (@NewsType=0)
     exec('SELECT TOP ' + @PageSize +' ID,Title,UpdateTime FROM News WHERE  SchoolID='+ @SchoolID +' AND ID NOT IN
  (SELECT TOP ' + @current +' ID FROM News WHERE SchoolID='+@SchoolID+' ORDER BY UpdateTime DESC)
  ORDER BY UpdateTime DESC')
 else
     exec('SELECT TOP ' + @PageSize +' ID,Title,UpdateTime FROM News WHERE  SchoolID='+ @SchoolID +' AND NewsType='+ @NewsType +' AND ID NOT IN
  (SELECT TOP ' + @current +' ID FROM News WHERE SchoolID='+@SchoolID+' AND NewsType='+@NewsType+' ORDER BY UpdateTime DESC)
  ORDER BY UpdateTime DESC')
 return
GO

转载于:https://www.cnblogs.com/happyhippy/archive/2007/01/29/633119.html

猜你喜欢

转载自blog.csdn.net/weixin_33676492/article/details/94676367
top