SQL分页读取数据-存储过程

CREATE proc sp_page
@pagenum int
as
SET NOCOUNT ON /*-----这一句很重要,不然它只会认 insert #change......这个数据集:))*/
declare @sql nvarchar(500) --声明动态sql执行语句
declare @pagecount int --当前页数

--取得当前数据库的记录总数
declare @row_num int
begin
select @row_num=count(*) from h_EmpArchives

--创建临时表,作为数据过滤
create table #change (T_id int)

--判断当前页数
if @row_num>50 --大于页面显示记录数,则分页
 begin
    set @row_num=@pagenum*50

      if @row_num=50
       select top 50 * from h_EmpArchives
    else
       begin
            set @row_num=(@pagenum-1)*50
            set @pagecount=@row_num
            set @sql=N'insert #change (T_id) select top '+cast(@pagecount as char(100))+' T_id from h_EmpArchives where T_id not in (select T_id from #change)'
            exec sp_executesql @sql
            select top 50 * from h_EmpArchives where T_id not in (select T_id from #change)
       end
    end
else --只现实全部的数据
 select * from h_EmpArchives
        end
GO

posted @ 2012-10-23 19:48  牛肉幹  阅读(155)  评论(0编辑  收藏  举报