分页存储过程sqlserver
存储过程:create Procere pname
( @pageIndex int,@pageSize)
as
select * from tableName order by id
offset @pageIndex * pageSize fetch next pageSize rows only
分页:
sqlserver 在2008之前 使用 top 和 not int top 的方式来做分页
2008以后使用 row_number() 函数作为分页关键函数
2012使用 offset 1 fetch next 10 rows only
你问了2个问题,你可以优先把视图,存储过程,触发器等弄明白,分页是查询,在存储过程里可以写复杂的sql文,只是在运行时是预编译和参数化查询防止sql注入
② SQL分页存储
SQLSERVER分页:
CREATE PROCEDURE UP_GetDataList
@tblName varchar(255), -- 表名
@strGetFields varchar(1000) = '*', -- 需要返回的列
@fldName varchar(255)='', -- 排序的字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@doCount bit = 0, -- 返回记录总数, 非 0 值则返回
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere nvarchar(1000) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL nvarchar(4000) -- 主语句
declare @strTmp varchar(110) -- 临时变量
declare @strOrder varchar(400) -- 排序类型
if @doCount != 0 --如果@doCount传递过来的不是0,就执行总数统计
begin
if @strWhere !=''
set @strSQL = 'SELECT COUNT(*) AS Total FROM ' + @tblName + ' WHERE ' + @strWhere
else
set @strSQL = 'SELECT COUNT(*) AS Total FROM ' + @tblName
end
else
begin
if @OrderType != 0
begin
set @strTmp = '<(SELECT MIN'
set @strOrder = ' ORDER BY [' + @fldName +'] DESC'
--如果@OrderType不是0,就执行降序
end
else
begin
set @strTmp = '>(SELECT MAX'
set @strOrder = ' ORDER BY [' + @fldName +'] ASC'
end
if @PageIndex = 1
begin
if @strWhere != ''
set @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' FROM [' + @tblName + '] WHERE ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' FROM ['+ @tblName + '] '+ @strOrder
--如果是第一页就执行以上代码,这样会加快执行速度
end
else
begin
--以下代码赋予了@strSQL以真正执行的SQL代码
set @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' FROM ['
+ @tblName + '] WHERE [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) FROM (SELECT TOP ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldName + '] FROM [' + @tblName + ']' + @strOrder + ') AS tblTmp)'+ @strOrder
if @strWhere != ''
set @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' FROM ['
+ @tblName + '] WHERE [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) FROM (SELECT TOP ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] FROM [' + @tblName + '] WHERE ' + @strWhere + ' '
+ @strOrder + ') AS tblTmp) AND ' + @strWhere + ' ' + @strOrder
end
end
exec (@strSQL)
GO
----------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Author: David.Yan
-- Create date: 2007.12.17
-- Description:
-- =============================================
Create PROC P_viewPage
-- Add the parameters for the stored procere here
@TableName VARCHAR(200), --表名
@FieldList VARCHAR(2000), --显示列名,如果是全部字段则为*
@PrimaryKey VARCHAR(100), --单一主键或唯一值键
@Where VARCHAR(2000), --查询条件 不含'where'字符,如id>10 and len(userid)>9
@Order VARCHAR(1000), --排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc
--注意当@SortType=3时生效,记住一定要在最后加上主键,否则会让你比较郁闷
@SortType INT, --排序规则 1:正序asc 2:倒序desc 3:多列排序方法
@RecorderCount INT, --记录总数 0:会返回总记录
@PageSize INT, --每页输出的记录数
@PageIndex INT, --当前页数
@TotalCount INT OUTPUT, --记返回总记录
@TotalPageCount INT OUTPUT --返回总页数
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
IF ISNULL(@TotalCount,'') = '' SET @TotalCount = 0
SET @Order = RTRIM(LTRIM(@Order))
SET @PrimaryKey = RTRIM(LTRIM(@PrimaryKey))
SET @FieldList = REPLACE(RTRIM(LTRIM(@FieldList)),' ','')
WHILE CHARINDEX(', ',@Order) > 0 OR CHARINDEX(' ,',@Order) > 0
BEGIN
SET @Order = REPLACE(@Order,', ',',')
SET @Order = REPLACE(@Order,' ,',',')
END
IF ISNULL(@TableName,'') = '' OR ISNULL(@FieldList,'') = ''
OR ISNULL(@PrimaryKey,'') = ''
OR @SortType < 1 OR @SortType >3
OR @RecorderCount < 0 OR @PageSize < 0 OR @PageIndex < 0
BEGIN
PRINT('ERR_00参数错误')
RETURN
END
IF @SortType = 3
BEGIN
IF (UPPER(RIGHT(@Order,4))!=' ASC' AND UPPER(RIGHT(@Order,5))!=' DESC')
BEGIN
PRINT('ERR_02排序错误') RETURN END
END
DECLARE @new_where1 VARCHAR(1000)
DECLARE @new_where2 VARCHAR(1000)
DECLARE @new_order1 VARCHAR(1000)
DECLARE @new_order2 VARCHAR(1000)
DECLARE @new_order3 VARCHAR(1000)
DECLARE @Sql VARCHAR(8000)
DECLARE @SqlCount NVARCHAR(4000)
IF ISNULL(@where,'') = ''
BEGIN
SET @new_where1 = ' '
SET @new_where2 = ' WHERE '
END
ELSE
BEGIN
SET @new_where1 = ' WHERE ' + @where
SET @new_where2 = ' WHERE ' + @where + ' AND '
END
IF ISNULL(@order,'') = '' OR @SortType = 1 OR @SortType = 2
BEGIN
IF @SortType = 1
BEGIN
SET @new_order1 = ' ORDER BY ' + @PrimaryKey + ' ASC'
SET @new_order2 = ' ORDER BY ' + @PrimaryKey + ' DESC'
END
IF @SortType = 2
BEGIN
SET @new_order1 = ' ORDER BY ' + @PrimaryKey + ' DESC'
SET @new_order2 = ' ORDER BY ' + @PrimaryKey + ' ASC'
END
END
ELSE
BEGIN
SET @new_order1 = ' ORDER BY ' + @Order
END
IF @SortType = 3 AND CHARINDEX(','+@PrimaryKey+' ',','+@Order)>0
BEGIN
SET @new_order1 = ' ORDER BY ' + @Order
SET @new_order2 = @Order + ','
SET @new_order2 = REPLACE(REPLACE(@new_order2,'ASC,','{ASC},'),'DESC,','{DESC},')
SET @new_order2 = REPLACE(REPLACE(@new_order2,'{ASC},','DESC,'),'{DESC},','ASC,')
SET @new_order2 = ' ORDER BY ' + SUBSTRING(@new_order2,1,LEN(@new_order2)-1)
IF @FieldList <> '*'
BEGIN
SET @new_order3 = REPLACE(REPLACE(@Order + ',','ASC,',','),'DESC,',',')
SET @FieldList = ',' + @FieldList
WHILE CHARINDEX(',',@new_order3)>0
BEGIN
IF CHARINDEX(SUBSTRING(','+@new_order3,1,CHARINDEX(',',@new_order3)),','+@FieldList+',')>0
BEGIN
SET @FieldList =
@FieldList + ',' + SUBSTRING(@new_order3,1,CHARINDEX(',',@new_order3))
END
SET @new_order3 = SUBSTRING(@new_order3,CHARINDEX(',',@new_order3)+1,LEN(@new_order3))
END
SET @FieldList = SUBSTRING(@FieldList,2,LEN(@FieldList))
END
END
SET @SqlCount = 'SELECT @TotalCount=COUNT(*),@TotalPageCount=CEILING((COUNT(*)+0.0)/'
+ CAST(@PageSize AS VARCHAR)+') FROM ' + @TableName + @new_where1
IF @RecorderCount = 0
BEGIN
EXEC SP_EXECUTESQL @SqlCount,N'@TotalCount INT OUTPUT,@TotalPageCount INT OUTPUT',
@TotalCount OUTPUT,@TotalPageCount OUTPUT
END
ELSE
BEGIN
SELECT @TotalCount = @RecorderCount
END
IF @PageIndex > CEILING((@TotalCount+0.0)/@PageSize)
BEGIN
SET @PageIndex = CEILING((@TotalCount+0.0)/@PageSize)
END
IF @PageIndex = 1 OR @PageIndex >= CEILING((@TotalCount+0.0)/@PageSize)
BEGIN
IF @PageIndex = 1 --返回第一页数据
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM '
+ @TableName + @new_where1 + @new_order1
END
IF @PageIndex >= CEILING((@TotalCount+0.0)/@PageSize) --返回最后一页数据
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ('
+ 'SELECT TOP ' + STR(ABS(@PageSize*@PageIndex-@TotalCount-@PageSize))
+ ' ' + @FieldList + ' FROM '
+ @TableName + @new_where1 + @new_order2 + ' ) AS TMP '
+ @new_order1
END
END
ELSE
BEGIN
IF @SortType = 1 --仅主键正序排序
BEGIN
IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2 --正向检索
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM '
+ @TableName + @new_where2 + @PrimaryKey + ' > '
+ '(SELECT MAX(' + @PrimaryKey + ') FROM (SELECT TOP '
+ STR(@PageSize*(@PageIndex-1)) + ' ' + @PrimaryKey
+ ' FROM ' + @TableName
+ @new_where1 + @new_order1 +' ) AS TMP) '+ @new_order1
END
ELSE --反向检索
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ('
+ 'SELECT TOP ' + STR(@PageSize) + ' '
+ @FieldList + ' FROM '
+ @TableName + @new_where2 + @PrimaryKey + ' < '
+ '(SELECT MIN(' + @PrimaryKey + ') FROM (SELECT TOP '
+ STR(@TotalCount-@PageSize*@PageIndex) + ' ' + @PrimaryKey
+ ' FROM ' + @TableName
+ @new_where1 + @new_order2 +' ) AS TMP) '+ @new_order2
+ ' ) AS TMP ' + @new_order1
END
END
IF @SortType = 2 --仅主键反序排序
BEGIN
IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2 --正向检索
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM '
+ @TableName + @new_where2 + @PrimaryKey + ' < '
+ '(SELECT MIN(' + @PrimaryKey + ') FROM (SELECT TOP '
+ STR(@PageSize*(@PageIndex-1)) + ' ' + @PrimaryKey
+' FROM '+ @TableName
+ @new_where1 + @new_order1 + ') AS TMP) '+ @new_order1
END
ELSE --反向检索
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ('
+ 'SELECT TOP ' + STR(@PageSize) + ' '
+ @FieldList + ' FROM '
+ @TableName + @new_where2 + @PrimaryKey + ' > '
+ '(SELECT MAX(' + @PrimaryKey + ') FROM (SELECT TOP '
+ STR(@TotalCount-@PageSize*@PageIndex) + ' ' + @PrimaryKey
+ ' FROM ' + @TableName
+ @new_where1 + @new_order2 +' ) AS TMP) '+ @new_order2
+ ' ) AS TMP ' + @new_order1
END
END
IF @SortType = 3 --多列排序,必须包含主键,且放置最后,否则不处理
BEGIN
IF CHARINDEX(',' + @PrimaryKey + ' ',',' + @Order) = 0
BEGIN
PRINT('ERR_02') RETURN
END
IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2 --正向检索
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
+ 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
+ ' SELECT TOP ' + STR(@PageSize*@PageIndex) + ' ' + @FieldList
+ ' FROM ' + @TableName + @new_where1 + @new_order1 + ' ) AS TMP '
+ @new_order2 + ' ) AS TMP ' + @new_order1
END
ELSE --反向检索
BEGIN
SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
+ 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
+ ' SELECT TOP ' + STR(@TotalCount-@PageSize *@PageIndex+@PageSize) + ' ' + @FieldList
+ ' FROM ' + @TableName + @new_where1 + @new_order2 + ' ) AS TMP '
+ @new_order1 + ' ) AS TMP ' + @new_order1
END
END
END
EXEC(@Sql)
GO
MYSQL分页:
DELIMITER $$
DROP PROCEDURE IF EXISTS `p_pageList`$$
/* m_pageNo 当前页码;
m_perPageCnt int ,每页显示条数;
m_column,查询的字段字符;
m_table,查询的表名;
m_condition,where条件(不用写where);
m_orderBy,排序条件(不用写order by);
m_totalPageCnt,查找的总条数*/
CREATE DEFINER=`root`@`%` PROCEDURE `p_pageList`(
m_pageNo int ,
m_perPageCnt int ,
m_column varchar(1000) ,
m_table varchar(1000) ,
m_condition varchar(1000),
m_orderBy varchar(200) ,
out m_totalPageCnt int
)
BEGIN
SET @pageCnt = 1; -- 总记录数
SET @limitStart = (m_pageNo - 1)*m_perPageCnt;
SET @limitEnd = m_perPageCnt;
SET @sqlCnt = CONCAT('select count(1) into @pageCnt from ',m_table); -- 这条语句很关键,用来得到总数值
-- @pageCnt变量为统计信息数
SET @sql = CONCAT('select ',m_column,' from ',m_table);
IF m_condition IS NOT NULL AND m_condition <> '' THEN -- 如果条件不为空
SET @sql = CONCAT(@sql,' where ',m_condition); -- 这条SQL语句为查找条件信息
SET @sqlCnt = CONCAT(@sqlCnt,' where ',m_condition); -- 这条SQL语句为查找条件信息的总数量
END IF;
IF m_orderBy IS NOT NULL AND m_orderBy <> '' THEN -- 如果排序条件不为空
SET @sql = CONCAT(@sql,' order by ',m_orderBy); -- SQL语句追加排序
END IF;
SET @sql = CONCAT(@sql, ' limit ', @limitStart, ',', @limitEnd); -- SQL语句添加分页信息
PREPARE s_cnt from @sqlCnt; -- 预处理SQL语句
EXECUTE s_cnt; -- 执行SQL语句
DEALLOCATE PREPARE s_cnt;
SET m_totalPageCnt = @pageCnt; -- 将值输出给 m_totalPageCnt变量
PREPARE record from @sql;
EXECUTE record;
DEALLOCATE PREPARE record;
END$$
DELIMITER ;
这两个应该都容易看懂,就算看不懂也没关系,只要知道传参数用就可以了。
③ sqlserver 存储过程分页
你可以采用 not in 方法
set @sql=' select top '+Str(@pageSize)+' * from dbo.LogManage where LogId not in(select top '+Str((@pageNumber-1)*@pageSize)+' LogId from LogManage order by LogId asc) as t'
④ SQLServer写一个分页的存储过程,要求取出101条到110条的内容,请问怎么写请给出具体的sql语句,谢谢。
转载的,能用!
------------
CREATE PROCEDURE Pagination
@tblName varchar(255), -- 表名
@strGetFields varchar(1000) = '*', -- 需要返回的列
@fldName varchar(255)='', -- 排序的字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@doCount bit = 0, -- 返回记录总数, 非 0 值则返回
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @d datetime
set @d=getdate()
declare @strSQL varchar(5000) -- 主语句
declare @strTmp varchar(110) -- 临时变量
declare @strOrder varchar(400) -- 排序类型
if @doCount != 0
begin
if @strWhere !=''
set @strSQL = 'select count(*) as Total from ['+ @tblName +'] where '+ @strWhere
else
set @strSQL = 'select count(*) as Total from ['+ @tblName +']'
end
--以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都
--是@doCount为0的情况
else
begin
if @OrderType != 0
begin
set @strTmp = '<(select min'
set @strOrder = ' order by ['+ @fldName +'] desc'
--如果@OrderType不是0,就执行降序,这句很重要!
end
else
begin
set @strTmp = '>(select max'
set @strOrder = ' order by ['+ @fldName +'] asc'
end
if @PageIndex = 1
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['+ @tblName +'] where ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['+ @tblName +'] '+ @strOrder
--如果是第一页就执行以上代码,这样会加快执行速度
end
else
begin
--以下代码赋予了@strSQL以真正执行的SQL代码
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from [' + @tblName +'] where [' + @fldName + ']' + @strTmp + '(['+ @fldName + '])
from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldName + '] from ['+ @tblName +']' + @strOrder + ') as tblTmp)'+ @strOrder
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['+ @tblName +'] where [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldName + ']
from ['+ @tblName +'] where ' + @strWhere + ' ' + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
end
end
exec ( @strSQL)
select datediff(ms,@d,getdate()) as 查询时间毫秒
go
Pagination 'CopyrightInformation','*','id',120,45667,0,0,''
⑤ SqlServer写真分页 存储过程报错 求大家帮忙帮忙看下消息 执行存储后 '@PageSize1' 附近有语法错误。
alter proc P_GetPagedAttManagerByCondition
@DeptID int,
@PageSize int,--一页显示的几条数据
@PageIndex int--当前是第几页
as
begin
Declare @sql1 nvarchar(2000),@sql2 nvarchar(2000),@sql nvarchar(2000)
set @sql1='select top (@PageSize1) u.UserID,u.UserName,d.DeptName from UserInfo u inner join Department d on u.DeptID=d.DeptID where u.DeptID=@id'
set @sql2='select top (@PageSize1*(@PageIndex1-1)) u.UserID from UserInfo u inner join Department d on u.DeptID=d.DeptID where u.DeptID=@id'
set @sql=@sql1+' and u.UserID not in'+'('+@sql2+')'
exec sp_executesql @sql,N'@id int,@PageSize1 int,@PageIndex1 int',@DeptID,@PageSize,@PageIndex
end
--set @sql1='select top (@PageSize1) 这里需要括号
-- set @sql=@sql1+' and 这里需要空格
⑥ sqlserver存储过程分页怎么写并且php怎么用adodb来调用存储过程,我只有这点分数了,谢谢了!
你这太麻烦了
给你个简单的
select top @pagesize @fieldlist from @tablename
where @strwhere and @keyfield
not in (select top @pagesize*(@pageindex-1) @keyfield from @tablename where @strwhere order by @keyfield desc )
order by @keyfield desc
⑦ sqlserver中定义好分页的存储过程,怎么使用存储过程查询
试试:
private DataTable GetDataByPageProc(String TableName, String Primarykey, String FieldsName, String ByWHERE
, String ByOrder, int PageSize, int PageIndex, ref int RecordCount, ref int PageCount)
{
SqlConnection cn = new SqlConnection(Function.ConnectionString);
String sql = "exec P_SlipPage @TableName=@a,@Primarykey=@b,@FieldsName=@c,@ByWHERE=@d ,@ByOrder=@e ,@PageSize=@f ,@PageIndex=@g ,@RecordCount=@h ,@PageCount =@i";
using (SqlDataAdapter da = new SqlDataAdapter(sql, cn))
{
da.SelectCommand.Parameters.AddWithValue("@a", TableName);
da.SelectCommand.Parameters.AddWithValue("@b", Primarykey);
da.SelectCommand.Parameters.AddWithValue("@c", FieldsName);
da.SelectCommand.Parameters.AddWithValue("@d", ByWHERE);
da.SelectCommand.Parameters.AddWithValue("@e", ByOrder);
da.SelectCommand.Parameters.AddWithValue("@f", PageSize);
da.SelectCommand.Parameters.AddWithValue("@g", PageIndex);
da.SelectCommand.Parameters.AddWithValue("@h", RecordCount);
da.SelectCommand.Parameters.AddWithValue("@i", PageCount);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
⑧ SQL Server 分页 查询语句
四种方式实现SQLServer 分页查询
SQLServer 的数据分页:
假设现在有这样的一张表:
CREATE TABLE test
(
id int primary key not null identity,
names varchar(20)
)
然后向里面插入大约1000条数据,进行分页测试
假设页数是10,现在要拿出第5页的内容,查询语句如下:
--10代表分页的大小
select top 10 *
from test
where id not in
(
--40是这么计算出来的:10*(5-1)
select top 40 id from test order by id
)
order by id
原理:需要拿出数据库的第5页,就是40-50条记录。首先拿出数据库中的前40条记录的id值,然后再拿出剩余部分的前10条元素
第二种方法:
还是以上面的结果为例,采用另外的一种方法
--数据的意思和上面提及的一样
select top 10 *
from test
where id >
(
select isnull(max(id),0)
from
(
select top 40 id from test order by id
) A
)
order by id
原理:先查询前40条记录,然后获得其最id值,如果id值为null的,那么就返回0
然后查询id值大于前40条记录的最大id值的记录。
这个查询有一个条件,就是id必须是int类型的。
第三种方法:
select top 10 *
from
(
select row_number() over(order by id) as rownumber,* from test
) A
where rownumber > 40
原理:先把表中的所有数据都按照一个rowNumber进行排序,然后查询rownuber大于40的前十条记录
这种方法和oracle中的一种分页方式类似,不过只支持2005版本以上的
第四种:
存储过程查询
创建存储过程
alter procere pageDemo
@pageSize int,
@page int
AS
declare @temp int
set @temp=@pageSize*(@page - 1)
begin
select top (select @pageSize) * from test where id not in (select top (select @temp) id from test) order by id
end
执行存储过程
exec 10,5