實現(xiàn)SQL分頁的存儲過程代碼
發(fā)布日期:2021-12-24 09:22 | 文章來源:源碼中國
SQL分頁的存儲過程代碼,需要的朋友們直接拿去用,使用非常簡單。
分享代碼如下
USE [SendMessage] GO /****** Object: StoredProcedure [dbo].[pages] Script Date: 07/09/2015 13:46:50 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROC [dbo].[pages] ( @tbname nvarchar(100), --要分頁顯示的表名 @FieldKey nvarchar(1000), --用于定位記錄的主鍵(惟一鍵)字段,可以是逗號分隔的多個字段 @PageCurrent int=1, --要顯示的頁碼 @PageSize int=10, --每頁的大小(記錄數(shù)) @FieldShow nvarchar(1000)='', --以逗號分隔的要顯示的字段列表,如果不指定,則顯示所有字段 @FieldOrder nvarchar(1000)='', --以逗號分隔的排序字段列表,可以指定在字段后面指定DESC/ASC @WhereString nvarchar(1000)=N'' --查詢條件 ) AS begin 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(@WhereString,N'')=N'' SET @WhereString=N'' ELSE SET @WhereString=N'WHERE '+@WhereString+N'' --計算分頁顯示的TOPN值 DECLARE @TopN varchar(20),@StartRecord varchar(20),@EndRecord varchar(20) SELECT @TopN=@PageSize, @StartRecord=(@PageCurrent-1)*@PageSize+1, @EndRecord=(@PageCurrent-1)*@PageSize+@PageSize --第一頁直接顯示 IF @PageCurrent=1 EXEC(N'SELECT TOP '+@TopN +N' '+@FieldShow +N' FROM '+@tbname +N' '+@WhereString +N' '+@FieldOrder) ELSE EXEC(N'with temptbl as( select ROW_NUMBER() Over('+@FieldOrder+') as row, '+@FieldKey+' from '+@tbname+N' '+@WhereString+') select '+@FieldShow+' from (select B.* from (select '+@FieldKey+' from temptbl where row between '+@StartRecord+' and '+@EndRecord+')A left join '+@tbname+' B on A.'+@FieldKey+'=B.'+@FieldKey+')C') END
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章