posts - 5,  comments - 5,  trackbacks - 0
CREATE PROCEDURE dbo.GetPagingRecord
    (
        @tablename varchar(100),--表名或视图表
        @fieldlist varchar(4000)='*',--欲选择字段列表
        @orderfield varchar(100),--排序字段
        @keyfield varchar(100),--主键
        @pageindex int,--页号,从1开始
        @pagesize int=20,--页尺寸
        @strwhere varchar(4000),--条件
        @ordertype varchar(1)='1'--排序,1,降序,0,升序
    )
AS

    SET NOCOUNT ON
    declare @sqlstr varchar(6000)
    declare @orderstr varchar(100)
    if(@keyfield=@orderfield)
    begin
 set @orderstr = ''
    end
    else
    begin
 set @orderstr = ','+@keyfield+' asc'
    end
    if @pageindex<=0
 set @pageindex=1
    --处理SQL中危险字符,并且将条件处理成易嵌入的形式
    set @strwhere=replace(@strwhere,'''','''''')
    set @strwhere=replace(@strwhere,'--','')
    set @strwhere=replace(@strwhere,';','')
    set @sqlstr='declare @CurPageNum int;'
    set @sqlstr=@sqlstr+'declare @nextpagenum int;'
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex-1 as varchar)+'*'+cast(@Pagesize as varchar)+';'
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';'
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);'
    if @ordertype='1'
    begin
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from 
 
'+@tablename+'  where 1=1 '+@strwhere+' order by '+@orderfield+' desc' + @orderstr+') as a where 1=1 and '+@keyfield+' not in ( 
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where 1=1 '+@strwhere+' 
 
order by '+@orderfield +' desc'+ @orderstr +') order by ' + @orderfield +' desc'';'
    end
    else
    begin
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from 
 
'+@tablename+'  where 1=1 '+@strwhere+' order by '+@orderfield+' asc' + @orderstr+' ) as a where 1=1 and '+@keyfield+' not in ( 
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where 1=1 '+@strwhere+' 
 
order by '+@orderfield +' asc' + @orderstr+') order by '+@orderfield +' asc'';'
    end
    set @sqlstr=@sqlstr+'execute( @sqlstr)'
    print @sqlstr
execute(@sqlstr)
GO

posted on 2007-07-06 08:54 曾科 阅读(218) 评论(0)  编辑  收藏 所属分类: SQL

只有注册用户登录后才能发表评论。


网站导航:
 
<2024年12月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(3)

随笔档案

文章分类

文章档案

相册

.net

搜索

  •  

最新评论

阅读排行榜

评论排行榜