存储过程实现(可带查询条件/万能分页/通用)
前端之家收集整理的这篇文章主要介绍了
存储过程实现(可带查询条件/万能分页/通用),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设数据库中有张表,表名是UserName,字段分别是ID(int),Name(nvarchar),Age(int)。
如果不带查询条件存储过程是
:
<div class="codetitle">
<a style="CURSOR: pointer" data="41833" class="copybut" id="copybut41833" onclick="doCopy('code41833')"> 代码如下:
<div class="codebody" id="code41833">
CREATE PROCEDURE [dbo].[UserName]
@pageIndex int,
@pageSize int
AS
declare @min int;
declare @max int;
set @min=@pageSize
(@pageIndex-1)+1;
set @max=@pageSize@pageIndex;
with myTable as(select ID,Name,Age,Row_Number() over (order by ID) as rownum from [UserName] )
select ID,Age from myTable where rownum between @min and @max
RETURN
这个
分页存储过程很不实用,并且表是固定的。
下面十二个万能分页存储过程
,
<div class="codetitle">
<a style="CURSOR: pointer" data="33547" class="copybut" id="copybut33547" onclick="doCopy('code33547')"> 代码如下:
<div class="codebody" id="code33547">
CREATE PROCEDURE [dbo].[UP_GetRecordByPage]
@tblName varchar(255),-- 表名
@fldName varchar(255),-- 主键字段名
@PageSize int,-- 页尺寸
@PageIndex int,--
页码 @IsReCount bit,-- 返回记录总数,非 0 值则返回
@OrderType bit,-- 设置排序类型,非 0 值则降序
@strWhere varchar(1000) = '' --
查询条件 (注意: 不要加 where)
AS
declare @str
sql varchar(6000) -- 主语句
declare @strTmp varchar(2000) -- 临时变量(
查询条件过长时可能会出错,可
修改100为1000)
declare @strOrder varchar(400) -- 排序类型
if @OrderType != 0
begin
set @strTmp = '<(select min'
set @strOrder = ' order by [' + @fldName +'] desc'
end
else
begin
set @strTmp = '>(select max'
set @strOrder = ' order by [' + @fldName +'] asc'
end
set @str
sql = 'select top ' + str(@PageSize) + '
from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
+ @strOrder
if @strWhere != ''
set @str
sql = 'select top ' + str(@PageSize) + '
from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
if @PageIndex <> 0
begin
set @strTmp =''
if @strWhere != ''
set @strTmp = ' where ' + @strWhere
set @str
sql = 'select top ' + str(@PageSize) + '
from ['
+ @tblName + ']' + @strTmp + ' ' + @strOrder
exec (@strsql)
end
if @IsReCount != 0
begin
set @strsql = 'select count() as Total from [' + @tblName + ']'+' where ' + @strWhere
exec (@str
sql)
end