createprocedure
[dbo
].[sp_tbtest_query](
@pagesize
int, --
每頁多少條記錄
@pageindex
int=
1, --
指定當前為第幾頁
@pagecount
int output, --
返回總頁數
@recordcount
int output, --
記錄總和
@orderfield
varchar(5000), --
排序字段(多欄位,不含order by)
@strwhere
varchar(5000), --
條件語句(不用加where)
@sumcolumnnames
nvarchar(200), --
彙總字段
@sumresult
nvarchar(200) output --
返回彙總結果)as
begin
declare
@sql
nvarchar(max) ='';
--條件處理
ifisnull(@strwhere, '') =
''begin
set@strwhere='
1=1
'end
--計算總記錄數
set@sql
= n'
select @a = count(*) from tbtest where '+
@strwhere
exec sp_executesql @sql, n'
@a int output
', @recordcount
output;
--計算總頁數
select
@pagecount
=ceiling(( @recordcount
+0.0 ) /
@pagesize
);
--處理頁數超出範圍情況
if@pageindex
<=
0set
@pageindex=1
;
if@pageindex
>
@pagecount
set@pageindex
=@pagecount
;
--處理開始點和結束點
declare
@startrecord
int;
declare
@endrecord
int;
set@startrecord
= ( @pageindex
-1 ) *
@pagesize+1
;
set@endrecord
=@startrecord
+@pagesize-1
;
--計算彙總
ifisnull(@sumcolumnnames, '') <>
''begin
set@sql
= n'
select @a = (cast(isnull(sum('+
replace(@sumcolumnnames, '
,','
), 0) as nvarchar(30)) + '',
''+ cast(isnull(sum(')
+'), 0) as nvarchar(30))) from tbtest where '+
@strwhere+'
'exec sp_executesql @sql, n'
@a nvarchar(200) output
', @sumresult
output;
end--
返回結果
set@sql
=n'select * from ( select * ,row_number() over(order by id desc) as rowid
from tbtest where '+
@strwhere
+n') t
where rowid between '+
convert(nvarchar(10),@startrecord)+n'
and '+
convert(nvarchar(10),@endrecord
)
exec sp_executesql @sql
end
declare@pagesize
int=
10, --
每頁多少條記錄
@pageindex
int=
2, --
指定當前為第幾頁
@pagecount
int , --
返回總頁數
@recordcount
int , --
記錄總和
@orderfield
varchar(5000)='id
', --
排序字段(多欄位,不含order by)
@strwhere
varchar(5000)=
'', --
條件語句(不用加where)
@sumcolumnnames
nvarchar(200)=
'age
', --
彙總字段
@sumresult
nvarchar(200) --
返回彙總結果
我在專案中遇到乙個問題,就是元資料由分組,然後再連線,為了加快查詢效率,我不得不剔除傳入where條件字串中的乙個條件,大概寫法如下:
declare @strwhere nvarchar(max)='id=1 and age=2 and address=''銷售部'''
declare @str1 nvarchar(max)=''
declare @str2 nvarchar(max)=''
if isnull(@strwhere, '')<>''
begin
if( charindex('age',@strwhere)>0 )
begin
set @str1 =substring(@strwhere,charindex('age',@strwhere),len(@strwhere))
if charindex('and',@str1)>0
begin
set @str2 =substring(@str1,charindex('and',@str1),len(@str1))
endset @strwhere=substring(@strwhere,0,charindex('age',@strwhere))+n' 1=1 '+@str2
endend
帶排序的oracle分頁儲存過程
create or replace package pager istype curs is ref cursor procedure pagination inpagesize in integer,每頁記錄數 inpageindex in integer,當前頁數 intablename in ...
帶排序的oracle分頁儲存過程
輸入order by 的sqeuence是,應該為 desc 或者 asc 若輸入兩個order by則,v order field a sequence order by b create or replace procedure tablepage select v page size int,...
sql 儲存過程分頁
create proc myx prpagerecordset querystr nvarchar 1000 keyfield nvarchar 200 pagesize int,pagenumber int as begin declare sqltext as nvarchar 4000 dec...