ROWNUMBER/Max/top 방식으로 스토리지 프로세스에 캡슐화

3391 단어
1、ROWNUMBER(    )
1 ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber]
2 (
3 @tbName VARCHAR(255), --
4 @tbGetFields VARCHAR(1000)= '*',--
5 @OrderfldName VARCHAR(255), --
6 @PageSize INT=20, --
7 @PageIndex INT=1, --
8 @OrderType bit = 0, --0 , 0
9 @strWhere VARCHAR(1000)='', --
10 --@TotalCount INT OUTPUT --
11 )
12 AS
13 -- =============================================
14 -- Author: allen (liyuxin)
15 -- Create date: 2012-03-30
16 -- Description: ( )
17 -- Modify [1]: 2012-03-30
18 -- =============================================
19 BEGIN
20 DECLARE @strSql VARCHAR(5000) --
21 DECLARE @strSqlCount NVARCHAR(500)--
22 DECLARE @strOrder VARCHAR(300) --
23
24 -------------- ---------------
25 IF ISNULL(@strWhere,'') <>''
26 SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where 1=1 '+ @strWhere
27 ELSE SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
28
29 --exec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output
30 -------------- ------------
31 IF @PageIndex <= 0 SET @PageIndex = 1
32
33 IF(@OrderType<>0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC '
34 ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC '
35
36 SET @strSql='SELECT * FROM
37 (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb
38 WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize)
39
40 exec(@strSql)
41 SELECT @TotalCount
42 END




2、Max/top
create proc [dbo].[spSqlPageByMaxTop]
@tbName varchar(255), --
@tbFields varchar(1000), --
@PageSize int, --
@PageIndex int, --
@strWhere varchar(1000), --
@StrOrder varchar(255), --
@Total int output --
as
declare @strSql varchar(5000) --
declare @strSqlCount nvarchar(500)--

-------------- ---------------
if @strWhere !=''
begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where '+ @strWhere
end
else
begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
end
-------------- ------------
if @PageIndex <= 0
begin
set @PageIndex = 1
end

set @strSql='select top '+str(@PageSize)+' * from ' + @tbName + '
where id>(select max(id) from (select top '+str((@PageIndex-1)*@PageSize)+' id from ' + @tbName + ''+@strOrder+')a)
'+@strOrder+''

exec sp_executesql @strSqlCount,N'@TotalCout int output',@Total output
exec(@strSql)

좋은 웹페이지 즐겨찾기