sql2005分頁存儲過程
1. 如何利用 vc ado 連接 sql Server2005 實現分頁存儲過程
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Proc_Util_Page]') AND OBJECTPROPERTY(id, N'IsProcere') = 1)
DROP PROCEDURE dbo.Proc_Util_Page
GO
/*
分頁
調用方法:EXEC Proc_Util_Page 'country,city', 'table', ' where 1=1', ' order by mid asc', 'mid', 1, 1, 0, ''
輸入:
1.欄位(不可為空)
2.表名(不可為空)
3.條件(可以為空,需要where)
4.排序(可以為空,需要order by,需要asc和desc字元)
5.主鍵(可以為空)
6.當前頁數
7.每頁記錄數
8.輸出總記錄條數(若<1則執行count)
9.輸出sql語句
返回:記錄集
*/
CREATE PROCEDURE dbo.Proc_Util_Page
(
@sField nvarchar(1000),
@sTable nvarchar(1000),
@sWhere nvarchar(1000),
@sOrderby nvarchar(1000),
@sPkey nvarchar(50),
@iPageIndex int,
@iPageSize int,
@iRecordCount int OUTPUT,
@sOutsql nvarchar(4000) OUTPUT
)
--WITH ENCRYPTION
AS
BEGIN
SET NOCOUNT ON
DECLARE @iRC int, @sSQL nvarchar(4000), @sW nvarchar(1000), @sOB nvarchar(1000), @sT nvarchar(100)
SELECT @iRC = @iRecordCount, @sSQL = '', @sW = ' WHERE 1=1 ', @sOB = ''
--判斷條件
IF RTRIM(@sWhere) != '' AND @sWhere IS NOT NULL
BEGIN
SET @sW=' ' + @sWhere + ' '
END
--判斷總記錄數
IF @iRC<1
BEGIN
SET @sSQL='SELECT @iRC=Count(*) FROM ' + @sTable + @sW
EXEC sp_executesql @sSQL,N'@iRC int OUT',@iRC OUT
END
--判斷頁數是否超出范圍
SELECT @iPageIndex=(CASE WHEN @iRC<(@iPageIndex-1)*@iPageSize THEN CEILING(@iRC/@iPageSize) WHEN @iPageIndex<1 THEN 1 ELSE @iPageIndex END)
--判斷排序
IF RTRIM(@sOrderby) != '' AND @sOrderby IS NOT NULL
BEGIN
SELECT @sOB=' ' + @sOrderby + ' '
END
--如果是第一頁
IF @iPageIndex=1
BEGIN
SET @sSQL='SELECT TOP '+CAST(@iPageSize AS nvarchar)+' '+@sField+' FROM '+@sTable+@sW+@sOB
GOTO step4
END
--看有否主鍵
IF RTRIM(@sPkey) = '' OR @sPkey IS NULL
GOTO step1
ELSE
--看是否按主鍵排序
BEGIN
DECLARE @sOB1 nvarchar(1000), @sPkey1 nvarchar(50)
SELECT @sOB1 = UPPER(@sOrderby), @sPkey1 = UPPER(@sPkey)
IF CHARINDEX(@sPkey1 + ' ASC', @sOB1)>0
BEGIN
SET @sT='>(SELECT MAX('
GOTO step2
END
IF CHARINDEX(@sPkey1 + ' DESC', @sOB1)>0
BEGIN
SET @sT='<(SELECT MIN('
GOTO step2
END
GOTO step3
END
--如果無主鍵
step1:
BEGIN
SET @sSQL='SELECT TOP '+CAST(@iPageSize AS nvarchar)+' '+@sField+' FROM '+@sTable+@sW + ' AND EXISTS (SELECT TOP '+CAST((@iPageIndex-1)*@iPageSize AS nvarchar)+' '+@sField+' FROM '+@sTable+@sW+@sOB+')'+@sOB+')'
GOTO step4
END
--純按主鍵排序
step2:
BEGIN
SET @sSQL='SELECT TOP '+CAST(@iPageSize AS nvarchar)+' '+@sField+' FROM '+@sTable+@sW+' AND '+@sPkey+@sT+@sPkey+') FROM (SELECT TOP '+CAST((@iPageIndex-1)*@iPageSize AS nvarchar)+' '+@sPkey+' FROM '+@sTable+@sW+@sOB+') AS tbTemp)'+@sOB
GOTO step4
END
--不純按主鍵排序
step3:
BEGIN
SET @sSQL='SELECT '+@sField+' FROM '+@sTable+@sW + ' AND ' + @sPkey+' IN (SELECT TOP '+CAST(@iPageSize AS nvarchar)+' '+@sPkey+' FROM '+@sTable+@sW + ' AND ' + @sPkey+' NOT IN(SELECT TOP '+CAST((@iPageIndex-1)*@iPageSize AS nvarchar)+' '+@sPkey+' FROM '+@sTable+@sW+@sOB+')'+@sOB+')'+@sOB
GOTO step4
END
--輸出最終執行的分頁sql語句並執行
step4:
SELECT @sOutsql = @sSQL, @iRecordCount = @iRC
--print(@sSQL)
EXEC(@sSQL)
SET NOCOUNT OFF
END
GO
---調用分頁存儲過程
declare @iRecordCount int,
@sOutsql nvarchar(4000)
EXEC Proc_Util_Page '欄位,欄位,欄位,欄位,欄位', '表名', ' where 1=1', ' order by id asc', 'id', 1, 10, @iRecordCount output, @sOutsql output
2. 求Sql Server2005分頁存儲過程
/*=======================================2008.3.19 笨笨熊 18071777=============================================================*/
Create procere [dbo].[Pager]
(
@Psql nvarchar(4000), --生成dataset的語句
@PNum int, --顯示第幾頁
@PSize int, --顯示多少條
@Sort nvarchar(200) = null, --排序語句 如:order by id desc
@RowNumName nvarchar(50), --ROW_NUMBER別名
@Prcount int out, --返回記錄總數
@Pcount int out --返回分頁總數
)
as
set nocount on
declare @sqlTmp nvarchar(1000) --存放SQL語句
declare @sqlTmpCount nvarchar(1000) --存放查詢記錄總數量SQL語句
--計算范圍
declare @Pmax int
declare @Pmin int
set @Pmax = @pnum*@psize --當前頁*頁大小 = 頁最大值
set @Pmin = @Pmax - @psize +1 --頁最大值 - 頁大小 + 1 = 頁最小值
set @sqlTmp='select * from ('+@Psql+')as temptb where '+@rowNumName+' BETWEEN '+cast(@Pmin as varchar(4))+' and '+cast(@Pmax as varchar(4))+''+@sort
set @sqlTmpCount='select @Prcount=count(*) from ('+@Psql+') as temptb'
----取得查詢記錄總數量-----
exec sp_executesql @sqlTmpCount,N'@Prcount int out ',@Prcount out
--取得分頁總數
set @Pcount=(@Prcount+@pSize-1)/@pSize
exec sp_executesql @sqlTmp
set nocount off
/*調用測試
declare @Prcount int
declare @Pcount int
exec Pager 'select row_number() over(order by picid) AS rownum,* FROM userpic',1,3,'','rownum',1,1
print @Pcount*/
業務層調用:
/// <summary>
/// 根據用戶自定義商品排序,分頁取得用戶收藏的商品
/// </summary>
/// <param name="pageIndex">當前頁索引</param>
/// <param name="pageSize">每頁記錄數</param>
/// <param name="recordCount">輸出參數:總記錄數</param>
/// <param name="pageCount">輸出參數:總頁數</param>
/// <returns>數據集(DataSet)</returns>
public DataSet GetShopsByPage(int pageIndex, int pageSize, out int recordCount, out int pageCount)
{
sql = "select row_number() over(order by picid) AS rownum,* FROM userpic";
return objDAO.GetDataByPage(sql, pageIndex, pageSize, "", "rownum", out recordCount, out pageCount);
}
數據訪問層方法:
/// <summary>
/// 函數: 執行分頁存儲過程 , 返回數據集,適用於Sqlserver2005資料庫
/// </summary>
/// <param name="psql">生成dataset的語句</param>
/// <param name="pNum">顯示第幾頁</param>
/// <param name="pSize">顯示多少條</param>
/// <param name="sort">排序語句 如:order by id desc </param>
/// <param name="rowNumName">ROW_NUMBER別名</param>
/// <param name="rCount">記錄總數</param>
/// <param name="pCount">頁總數</param>
/// <returns>返回數據集</returns>
public override DataSet GetDataByPage(string psql, int pNum, int pSize, string sort, string rowNumName, out int rCount, out int pCount)
{
OpenConn();
sqlCmd = new SqlCommand("Pager", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcere;
sqlCmd.Parameters.Add("@Psql", SqlDbType.NVarChar).Value = psql;
sqlCmd.Parameters.Add("@pNum", SqlDbType.Int).Value = pNum;
sqlCmd.Parameters.Add("@Psize", SqlDbType.Int).Value = pSize;
sqlCmd.Parameters.Add("@sort", SqlDbType.NVarChar).Value = sort;
sqlCmd.Parameters.Add("@rowNumName", SqlDbType.NVarChar).Value = rowNumName;
sqlCmd.Parameters.Add("@Prcount", SqlDbType.Int).Direction = ParameterDirection.Output;
sqlCmd.Parameters.Add("@Pcount", SqlDbType.Int).Direction = ParameterDirection.Output;
//數據集對象
ds = new DataSet();
sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = sqlCmd;
//數據填充
sqlDa.Fill(ds);
//從輸出參數中讀取[總記錄數]
rCount = (int)sqlCmd.Parameters["@Prcount"].Value;
//從輸出參數中讀取[總頁數]
pCount = (int)sqlCmd.Parameters["@Pcount"].Value;
CloseConn();
return ds;
}
3. SQL Server 2005存儲過程分頁排序設置列名為變數
用字元串的方式來做,先生成查詢字元串,然後執行
/*******************************************************************************
Author : Richard.Cai
CreateDate : 2008-12-22
UpdateDate : 2008-12-25
Amendment History:
Update by $$$$$$$$$$$ 2008/12/25 : Alter content.
*******************************************************************************/
ALTER PROCEDURE [dbo].[USP_AT_MR_SearchClient]
(
@PageSize INT = 10 --The size per page
,@PageStart INT = 0 --The page start,not contain this no..
,@WhereStr NVARCHAR(MAX) = '' --For example:' AND ClientName like '%AS%''
,@DebugFlag BIT = 0
)
AS
DECLARE @TableName NVARCHAR(255) --Only a table name
DECLARE @FieldName NVARCHAR(255) --Field name that data is unique.
DECLARE @sSQL NVARCHAR(MAX)
DECLARE @sTMP NVARCHAR(MAX)
DECLARE @sOrderBy NVARCHAR(255)
/*Generate Paging Data*/
SELECT @sSQL=N'SELECT '+CHAR(13)
+N' ROW_NUMBER() OVER(ORDER BY SysID) AS PageID '+CHAR(13)
+N' ,Client_id As ClientCode '+CHAR(13)
+N' ,CAST(RTRIM(Client_e) AS NVARCHAR(50)) As ClientName '+CHAR(13)
+N' ,CAST(RTRIM(Client_c) AS NVARCHAR(50)) As ClientNameLocal '+CHAR(13)
+N'INTO #Client '+CHAR(13)
+N'FROM Client '+CHAR(13)
+N'WHERE 1 = 1 ' + @WhereStr +CHAR(13)
+N' '+CHAR(13)
+N'SELECT * FROM #Client '+CHAR(13)
+N'WHERE PageID > ' + RTRIM(@PageStart) + ' AND PageID <= ' + RTRIM(@PageStart+@PageSize)+CHAR(13)
+N' '
+N'SELECT COUNT(*) As TotalCount FROM #Client'
IF @DebugFlag = 1
PRINT '/*Paging SQL:*/'+CHAR(13)+@sSQL
EXEC SP_EXECUTESQL @sSQL
4. 高分求SQL分頁的存儲過程
ASP.Net中的DataGrid有內置分頁功能,
但是它的默認的分頁方式效率是很低的,特別是在數據量很大的時候,用它內置的分頁功能幾乎是不可能的事,因為它會把所有的數據從資料庫讀出來再進行分頁,
這種只選取了一小部分而丟掉大部分的方法是不可去取的.
在最進的一個項目中因為一個管理頁面要管理的數據量非常大,所以必須分頁顯示,並且不能用DataGrid的內置分頁功能,於是自己實現分頁.
下面介紹一下我在項目中用到的分頁方法.
當然顯示控制項還是用DataGrid的,
因為數據綁定很方便^_^.
要保證不傳輸冗餘的數據,那麼必須在資料庫中數據讀取時實現分頁,
資料庫的分頁操作可以放在存儲過程中.
看了CSDN的一篇Blog中講了一個百萬級數據分頁的存儲過程的實現(
http://blog.csdn.net/wellknow/posts/55167.aspx
,他的這個方法可以根據不同情況進行適當的優化),
根據他的方法,這里實現一個簡單的SQL語句來實現這里分頁需要的存儲過程。
create
procere
ListProct
(
@PageIndex
int,
--
分頁後需要頁的序號
@PageSize
int,
--
一頁的大小
@ConditionSQL
–
查詢條件的SQL語句
)
AS
…
具體代碼就不寫了(可以參考上面的鏈接).
具體的SQL語句如下:
Select
TOP
100
*
FROM
(select
*
from
proct
where
proctid<200000)
T
Where
T.proctid
NOT
IN
(Select
TOP
900
proctid
FROM
(select
proctid
from
proct
where
proctid<200000)
T1
orDER
BY
T1.proctid
asc)
orDER
BY
proctid
asc
這條語句的
從總的商品(30萬)中取出proctid<200000(共20萬),再按每頁100的大小分頁,然後取出第10頁.
Public
DataTable
ListProct(int
pageIndex,
int
pageSize)
{
//ADO.net從資料庫中取出數據的代碼就略過^_^.
}
用上面的存儲過程讀出的數據在DataGrid裡面分頁,
必須把DataGrid的AllowPaging和AllowCustomPaging設置為true
protected
System.Web.UI.WebControls.DataGrid
ProctGrid;
ProctGrid.AllowPaging
=
true;
ProctGrid.AllowCustomPaging
=
true;
然後在設置要顯示的一頁的大小
ProctGrid.PageSize
=
100;
//
在顯示的時候依據實際的數據顯示。
設置一頁大小後,如果要讓DataGrid實際分出頁數來,還必須設置
ProctGrid.VirtualItemCount
=
GetProctCount()
;
//
GetProctCount()
的功能是獲取滿足條件的產品數目,
這里的條件就是proctid<200000.
設置這項屬性後,那麼這個DataGrid的頁數就是
VirtualItemCount/PageSize,
也就是PageCount的值.
不能對PageCount直接賦值,因為他是只讀的屬性.
5. 用Sql寫一個分頁查詢的存儲過程 表stuinfo主鍵stuno
隨便你怎麼填!
/****** 對象: StoredProcere [dbo].[usp_DataPagination_v1] 腳本日期: 09/03/2010 16:52:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_DataPagination_v1]
(
@tblName nvarchar(200), ----要顯示的表或多個表的連接
@fldName nvarchar(500) = '*', ----要顯示的欄位列表
@pageSize int = 10, ----每頁顯示的記錄個數
@page int = 1, ----要顯示那一頁的記錄
@pageCount int = 1 output, ----查詢結果分頁後的總頁數
@Counts int = 1 output, ----查詢到的記錄數
@fldSort nvarchar(200), ----排序欄位列表或條件
@Sort bit = 0, ----排序方法,0為升序,1為降序(如果是多欄位排列Sort指代最後一個排序欄位的排列順序(最後一個排序欄位不加排序標記)--程序傳參如:' SortA Asc,SortB Desc,SortC ')
@strCondition nvarchar(2000) = null, ----查詢條件,不需where
@ID nvarchar(150), ----主表的主鍵
@Dist bit = 0 ----是否添加查詢欄位的 DISTINCT 默認0不添加/1添加
)
AS
SET NOCOUNT ON
Declare @sqlTmp nvarchar(1000) ----存放動態生成的SQL語句
Declare @strTmp nvarchar(max) ----存放取得查詢結果總數的查詢語句
Declare @strID nvarchar(1000) ----存放取得查詢開頭或結尾ID的查詢語句
Declare @strSortType nvarchar(10) ----數據排序規則A
Declare @strFSortType nvarchar(10) ----數據排序規則B
Declare @SqlSelect nvarchar(50) ----對含有DISTINCT的查詢進行SQL構造
Declare @SqlCounts nvarchar(50) ----對含有DISTINCT的總數查詢進行SQL構造
if @Dist = 0
begin
set @SqlSelect = 'select '
set @SqlCounts = 'Count(*)'
end
else
begin
set @SqlSelect = 'select distinct '
set @SqlCounts = 'Count(DISTINCT '+@ID+')'
end
if @Sort=0
begin
set @strFSortType=' ASC '
set @strSortType=' DESC '
end
else
begin
set @strFSortType=' DESC '
set @strSortType=' ASC '
end
--------生成查詢語句--------
--此處@strTmp為取得查詢結果數量的語句
if @strCondition is null or @strCondition='' --沒有設置顯示條件
begin
set @sqlTmp = @fldName + ' From ' + @tblName
set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName
set @strID = ' From ' + @tblName
end
else
begin
set @sqlTmp = + @fldName + 'From ' + @tblName + ' where (1>0) ' + @strCondition
set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName + ' where (1>0) ' + @strCondition
set @strID = ' From ' + @tblName + ' where (1>0) ' + @strCondition
end
----取得查詢結果總數量-----
exec sp_executesql @strTmp,N'@Counts int out ',@Counts out
declare @tmpCounts int
if @Counts = 0
set @tmpCounts = 1
else
set @tmpCounts = @Counts
--取得分頁總數
set @pageCount=(@tmpCounts+@pageSize-1)/@pageSize
/**//**當前頁大於總頁數 取最後一頁**/
if @page>@pageCount
set @page=@pageCount
--/*-----數據分頁2分處理-------*/
declare @pageIndex int --總數/頁大小
declare @lastcount int --總數%頁大小
set @pageIndex = @tmpCounts/@pageSize
set @lastcount = @tmpCounts%@pageSize
if @lastcount > 0
set @pageIndex = @pageIndex + 1
else
set @lastcount = @pagesize
--//***顯示分頁
if @strCondition is null or @strCondition='' --沒有設置顯示條件
begin
if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2 --前半部分數據處理
begin
set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName
+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName
+' order by '+ @fldSort +' '+ @strFSortType+')'
+' order by '+ @fldSort +' '+ @strFSortType
end
else
begin
set @page = @pageIndex-@page+1 --後半部分數據處理
if @page <= 1 --最後一頁數據顯示
set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(4))+' '+ @fldName+' from '+@tblName
+' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType
else
set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName
+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName
+' order by '+ @fldSort +' '+ @strSortType+')'
+' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType
end
end
else --有查詢條件
begin
if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2 --前半部分數據處理
begin
set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName +' from '+@tblName
+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName
+' Where (1>0) ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType+')'
+' ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType
end
else
begin
set @page = @pageIndex-@page+1 --後半部分數據處理
if @page <= 1 --最後一頁數據顯示
set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(4))+' '+ @fldName+' from '+@tblName
+' where (1>0) '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType
else
set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName
+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName
+' where (1>0) '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+')'
+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType
end
end
------返回查詢結果-----
exec sp_executesql @strTmp
print @strTmp
SET NOCOUNT OFF
這已經是很成熟的了。。。。很精簡。。你要分頁的話基本都是輸入這點參數。50萬條數據測試5秒內
6. sql server 2005 存儲過程分頁怎麼做
SET
ANSI_NULLS
ON
GO
SET
QUOTED_IDENTIFIER
ON
GO
CREATE
proc
[dbo].[up_Page2005]
@TableName
varchar(50),
--表名
@Fields
varchar(5000)
=
'*',
--欄位名(全部欄位為*)
@OrderField
varchar(5000),
--排序欄位(必須!支持多欄位)
@sqlWhere
varchar(5000)
=
Null,--條件語句(不用加where)
@pageSize
int,
--每頁多少條記錄
@pageIndex
int
=
1
,
--指定當前為第幾頁
@TotalPage
int
output
--返回總頁數
as
begin
Begin
Tran
--開始事務
Declare
@sql
nvarchar(4000);
Declare
@totalRecord
int;
--計算總記錄數
if
(@SqlWhere=''
or
@sqlWhere=NULL)
set
@sql
=
'select
@totalRecord
=
count(*)
from
'
+
@TableName
else
set
@sql
=
'select
@totalRecord
=
count(*)
from
'
+
@TableName
+
'
with(nolock)
where
'
+
@sqlWhere
EXEC
sp_executesql
@sql,N'@totalRecord
int
OUTPUT',@totalRecord
OUTPUT--計算總記錄數
--計算總頁數
select
@TotalPage=CEILING((@totalRecord+0.0)/@PageSize)
if
(@SqlWhere=''
or
@sqlWhere=NULL)
set
@sql
=
'Select
*
FROM
(select
ROW_NUMBER()
Over(order
by
'
+
@OrderField
+
')
as
rowId,'
+
@Fields
+
'
from
'
+
@TableName
else
set
@sql
=
'Select
*
FROM
(select
ROW_NUMBER()
Over(order
by
'
+
@OrderField
+
')
as
rowId,'
+
@Fields
+
'
from
'
+
@TableName
+
'
with(nolock)
where
'
+
@SqlWhere
--處理頁數超出范圍情況
if
@PageIndex<=0
Set
@pageIndex
=
1
if
@pageIndex>@TotalPage
Set
@pageIndex
=
@TotalPage
--處理開始點和結束點
Declare
@StartRecord
int
Declare
@EndRecord
int
set
@StartRecord
=
(@pageIndex-1)*@PageSize
+
1
set
@EndRecord
=
@StartRecord
+
@pageSize
-
1
--繼續合成sql語句
set
@Sql
=
@Sql
+
')
as
t
where
rowId
between
'
+
Convert(varchar(50),@StartRecord)
+
'
and
'
+
Convert(varchar(50),@EndRecord)
print
@sql
Exec(@Sql)
---------------------------------------------------
If
@@Error
<>
0
Begin
RollBack
Tran
Return
-1
End
Else
Begin
Commit
Tran
Return
@totalRecord
---返回記錄總數
End
end
7. sql存儲過程定義多條件查詢加分頁
給你一個強大至極的分頁存儲過程(輸入對應的參加即可),以此共勉,希望你也能進步:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Pagination]
@Page int = 1, -- 當前頁碼
@PageSize int = 10, -- 每頁記錄條數(頁面大小)
@Table nvarchar(500), -- 表名或視圖名,甚至可以是嵌套SQL:(Select * From Tab Where ID>1000) Tab
@Field nvarchar(800) = '*', -- 返回記錄集欄位名,","隔開,默認是"*"
@OrderBy nvarchar(100) = 'ID ASC', -- 排序規則
@Filter nvarchar(500), -- 過濾條件
@MaxPage smallint output, -- 執行結果 -1 error, 0 false, maxpage true
@TotalRow int output, -- 記錄總數 /* 2007-07-12 22:11:00 update */
@Descript varchar(100) output -- 結果描述
AS
BEGIN
-- =============================================
-- Author: Jimmy.Yu
-- Create date: 2007-5-11
-- Description: SQL 2005 以上版本 通用分頁存儲過程
-- =============================================
Set ROWCOUNT @PageSize;
Set @Descript = 'successful';
-------------------參數檢測----------------
IF LEN(RTRIM(LTRIM(@Table))) !> 0
Begin
Set @MaxPage = 0;
Set @Descript = 'table name is empty';
Return;
End
IF LEN(RTRIM(LTRIM(@OrderBy))) !> 0
Begin
Set @MaxPage = 0;
Set @Descript = 'order is empty';
Return;
End
IF ISNULL(@PageSize,0) <= 0
Begin
Set @MaxPage = 0;
Set @Descript = 'page size error';
Return;
End
IF ISNULL(@Page,0) <= 0
Begin
Set @MaxPage = 0;
Set @Descript = 'page error';
Return;
End
-------------------檢測結束----------------
Begin Try
-- 整合SQL
Declare @SQL nvarchar(4000), @Portion nvarchar(4000);
Set @Portion = ' ROW_NUMBER() OVER (ORDER BY ' + @OrderBy + ') AS ROWNUM FROM ' + @Table;
Set @Portion = @Portion + (CASE WHEN LEN(@Filter) >= 1 THEN (' Where ' + @Filter + ') AS tab') ELSE (') AS tab') END);
Set @SQL = 'Select TOP(' + CAST(@PageSize AS nvarchar(8)) + ') ' + @Field + ' FROM (Select ' + @Field + ',' + @Portion;
Set @SQL = @SQL + ' Where tab.ROWNUM > ' + CAST((@Page-1)*@PageSize AS nvarchar(8));
-- 執行SQL, 取當前頁記錄集
Execute(@SQL);
--------------------------------------------------------------------
-- 整合SQL
Set @SQL = 'Set @Rows = (Select MAX(ROWNUM) FROM (Select' + @Portion + ')';
-- 執行SQL, 取最大頁碼
Execute sp_executesql @SQL, N'@Rows int output', @TotalRow output;
Set @MaxPage = (CASE WHEN (@TotalRow % @PageSize)<>0 THEN (@TotalRow / @PageSize + 1) ELSE (@TotalRow / @PageSize) END);
End Try
Begin Catch
-- 捕捉錯誤
Set @MaxPage = -1;
Set @Descript = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return;
End Catch;
-- 執行成功
Return;
END
8. sql server 分頁存儲過程
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 @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)
GO
/*
-- 需要傳遞的參數
@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)
-- 調用測試
exec pagination @tblName='jobs', @strGetFields='job_id,job_desc,min_lvl,max_lvl',
@fldName='job_id',@PageSize=3,@PageIndex=1,
@doCount=0,@OrderType=1,@strWhere=''
*/
============================================
CREATE PROC SP_PageList
@tbname sysname, --要分頁顯示的表名
@FieldKey sysname, --用於定位記錄的主鍵(惟一鍵)欄位,只能是單個欄位
@PageCurrent int=1, --要顯示的頁碼
@PageSize int=10, --每頁的大小(記錄數)
@FieldShow nvarchar(1000)='', --以逗號分隔的要顯示的欄位列表,如果不指定,則顯示所有欄位
@FieldOrder nvarchar(1000)='', --以逗號分隔的排序欄位列表,可以指定在欄位後面指定DESC/ASC
--用於指定排序順序
@Where nvarchar(1000)='', --查詢條件
@RecordCount int OUTPUT, --總記錄數
@PageCount int OUTPUT --總頁數
AS
DECLARE @sql nvarchar(4000)
SET NOCOUNT ON
--檢查對象是否有效
IF OBJECT_ID(@tbname) IS NULL
BEGIN
RAISERROR(N'對象"%s"不存在',1,16,@tbname)
RETURN
END
IF OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTable')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsView')=0
AND OBJECTPROPERTY(OBJECT_ID(@tbname),N'IsTableFunction')=0
BEGIN
RAISERROR(N'"%s"不是表、視圖或者表值函數',1,16,@tbname)
RETURN
END
--分頁欄位檢查
IF ISNULL(@FieldKey,N'')=''
BEGIN
RAISERROR(N'分頁處理需要主鍵(或者惟一鍵)',1,16)
RETURN
END
--其他參數檢查及規范
IF ISNULL(@PageCurrent,0)<1 SET @PageCurrent=1
IF ISNULL(@PageSize,0)<1 SET @PageSize=10
IF ISNULL(@FieldShow,N'')=N'' SET @FieldShow=N'*'
IF ISNULL(@FieldOrder,N'')=N''
SET @FieldOrder=N''
ELSE
SET @FieldOrder=N'ORDER BY '+LTRIM(@FieldOrder)
IF ISNULL(@Where,N'')=N''
SET @Where=N''
ELSE
SET @Where=N'WHERE ('+@Where+N')'
--如果@PageCount為NULL值,則計算總頁數(這樣設計可以只在第一次計算總頁數,以後調用時,把總頁數傳回給存儲過程,避免再次計算總頁數,對於不想計算總頁數的處理而言,可以給@PageCount賦值)
IF @PageCount IS NULL
BEGIN
SET @sql=N'SELECT @PageCount=COUNT(*)'
+N' FROM '+@tbname
+N' '+@Where
EXEC sp_executesql @sql,N'@PageCount int OUTPUT',@PageCount OUTPUT
SET @RecordCount = @PageCount
SET @PageCount=(@PageCount+@PageSize-1)/@PageSize
END
--計算分頁顯示的TOPN值
DECLARE @TopN varchar(20),@TopN1 varchar(20)
SELECT @TopN=@PageSize,
@TopN1=@PageCurrent*@PageSize
--第一頁直接顯示
IF @PageCurrent=1
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' '+@Where
+N' '+@FieldOrder)
ELSE
BEGIN
SELECT @PageCurrent=@TopN1,
@sql=N'SELECT @n=@n-1,@s=CASE WHEN @n<'+@TopN
+N' THEN @s+N'',''+QUOTENAME(RTRIM(CAST('+@FieldKey
+N' as varchar(8000))),N'''''''') ELSE N'''' END FROM '+@tbname
+N' '+@Where
+N' '+@FieldOrder
SET ROWCOUNT @PageCurrent
EXEC sp_executesql @sql,
N'@n int,@s nvarchar(4000) OUTPUT',
@PageCurrent,@sql OUTPUT
SET ROWCOUNT 0
IF @sql=N''
EXEC(N'SELECT TOP 0'
+N' '+@FieldShow
+N' FROM '+@tbname)
ELSE
BEGIN
SET @sql=STUFF(@sql,1,1,N'')
--執行查詢
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' WHERE '+@FieldKey
+N' IN('+@sql
+N') '+@FieldOrder)
END
END
GO