set quoted_identifier on
go
set ansi_nulls on
go
create proc execbypage
@sqlquery varchar(2000), --//输入参数:sql检索语句或表名
@pagesize int, --//输入参数:每页显示记录条数
@pageindex int --//输入参数:当前页码
as
set nocount on
set ansi_warnings off
declare @tmptablename varchar(50)
set @tmptablename = '##tb1516_' + replace(cast(newid() as varchar(40)),'-','') --//生成随机临时表名称
declare @subindex int
set @subindex = charindex('from',@sqlquery)
if (@subindex > 0)
begin --//带from的标准检索语句
declare @sqlquery1 varchar(2000)
declare @sqlquery2 varchar(2000)
set @sqlquery1 = substring(@sqlquery,1,@subindex - 1)
set @sqlquery2 = substring(@sqlquery,@subindex,len(@sqlquery))
set @sqlquery = @sqlquery1 + ',identity(numeric,1,1) as id1516 into ' + @tmptablename + ' ' + @sqlquery2
end
else --//不带from的表名
begin
set @sqlquery = 'select *,identity(numeric,1,1) as id1516 into ' + @tmptablename + ' from' + @sqlquery
end
exec(@sqlquery) --//建立并初始化临时表数据
declare @indexstart varchar(20),@indexend varchar(20)
set @indexstart = cast((@pageindex-1)*@pagesize+1 as varchar(20)) --//数据起始行id
set @indexend = cast(@pageindex * @pagesize as varchar(20)) --//数据结束行id
exec('select * from ' + @tmptablename + ' where id1516 between ' + @indexstart + ' and ' + @indexend) --//检索该页数据
exec('select max(id1516) as recordcount from ' + @tmptablename) --//提取总条数
exec('drop table ' + @tmptablename) --//删除临时表
go
set quoted_identifier off
go
set ansi_nulls on
go