moonshine

导航

分页存储过程

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO


--返回数据表中指定页的数据,页面中的数据行数,页数需要指定
--2006-03-10

ALTER        procedure pt_GetSearchResult 
( @TableName NVarChar(100),--表名
 @UniqueColumeName NVarChar(100),--表中的ID列名称
 @VcharCondiction NVarChar(100), --查询条件
 @PageSize int,
 @PageIndex int,
 @docount bit) 
as 
--定义变量
declare @cTemp NVarChar(200),@indextable NVarChar(100)

--默认将表的唯一列的列名设置成ID
if @UniqueColumeName =''
set @UniqueColumeName = 'ID'

set nocount on 
--得到记录总数
if(@docount=1) 
 begin
  set @cTemp = 'select count(*) from '+@tableName + ' '+ @VcharCondiction
  
  exec (@cTemp)
 end
else 
--得到结果集
 begin 
  
  set @indextable =   cast(cast( RAND ()*1000 as int) as varchar)
  set @indextable ='##temAspPage' + @indextable
   --判断定义的临时表是否已经存在
  IF EXISTS(SELECT name FROM tempdb.dbo.sysobjects
    WHERE  name = @indextable   AND   type = 'U')
  begin
    --如果存在 删除临时表
    set @cTemp =  N' DROP TABLE ' +@indextable
    exec (@cTemp)
  end

  --创建临时表和索引
  set @cTemp =  N' create table '+@indextable+'(id bigint identity(1,1),nid bigint)'+
    ' CREATE UNIQUE CLUSTERED INDEX indextable_ind   ON ' +@indextable +'(id)'

  exec (@cTemp)
  

  declare @PageLowerBound int 
  declare @PageUpperBound int 
  set @PageLowerBound=(@pageindex-1)*@pagesize 
  set @PageUpperBound=@PageLowerBound+@pagesize 
  set rowcount @PageUpperBound 
  
  --将符合条件的nid 记录到表里
  set @cTemp = 'insert into  '+@indextable+'(nid) select newsid from wqnews  '+ @VcharCondiction
  --print @cTemp
  exec (@cTemp)
  
  --将符合条件的结果集显示出来
  set @cTemp='  select O.newsid,O.heading,O.source,O.author,O.addtime from wqnews O,'+ 
    @indextable + ' t where O.newsid=t.nid  and t.id> '+ 
    cast(@PageLowerBound as varchar) + ' and t.id<= '+
    cast(@PageUpperBound as varchar)  + ' order by t.id  '
  print @cTemp
  
  exec (@cTemp)
 
  --删除此次临时表
  set @cTemp =  N' DROP TABLE ' +@indextable
  exec (@cTemp)

 end 

set nocount off 

 

--dbo.pt_GetSearchResult 'wqnews','newsid','',20,1000,0

 

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

 

posted on 2006-03-10 09:20    阅读(51)  评论(0)    收藏  举报