SQL 存储过程分页 示例
SQL 存储过程分页 示例
Code
create PROCEDURE [dbo].[pro_sample]
@pi_int_category_id_path varchar(20),
@pi_vch_user_id varchar(20),
@pi_int_page_index INT,
@pi_int_page_size INT,
@po_int_total_count int OUTPUT
AS
BEGIN
declare @query_select varchar(3000);
declare @query_where varchar(1000);
declare @query_select_count nvarchar(3000);
declare @query_start int;
declare @query_end int;
set @query_start = (@pi_int_page_index - 1) * @pi_int_page_size;
set @query_end = @pi_int_page_index * @pi_int_page_size;
set @query_select = '
SELECT
row_number() over (order by [create_time] )as rownumber
,[a]
,[b]
,[c]
FROM [dbo].[tbl_inner_table1]
';
set @query_where = ' where 1 = 1 ';
set @query_where = @query_where + ' and [category_path] = ''' + @pi_int_category_id_path + '''
and [user_id] = ''' + @pi_vch_user_id + '''
and [state] != ''3''';
--合并
set @query_select = N'with temp_table AS
(' + @query_select + @query_where + ')
select * from temp_table
where rownumber > ' + convert(varchar(20), @query_start) + '
and rownumber <=' + convert(varchar(20), @query_end);
--总数
set @query_select_count = N'WITH temp_table AS
(
SELECT 1 RowNumber
FROM [dbo].[tbl_inner_table1]
'+ @query_where +' )
select @po_int_total_count = count(1) from temp_table ';
--执行
EXEC SP_EXECUTESQL @query_select_count, N'@po_int_total_count INT OUTPUT ', @po_int_total_count OUTPUT;
--print(@query_select_count);
--print(@query_select);
exec(@query_select);
END
create PROCEDURE [dbo].[pro_sample]
@pi_int_category_id_path varchar(20),
@pi_vch_user_id varchar(20),
@pi_int_page_index INT,
@pi_int_page_size INT,
@po_int_total_count int OUTPUT
AS
BEGIN
declare @query_select varchar(3000);
declare @query_where varchar(1000);
declare @query_select_count nvarchar(3000);
declare @query_start int;
declare @query_end int;
set @query_start = (@pi_int_page_index - 1) * @pi_int_page_size;
set @query_end = @pi_int_page_index * @pi_int_page_size;
set @query_select = '
SELECT
row_number() over (order by [create_time] )as rownumber
,[a]
,[b]
,[c]
FROM [dbo].[tbl_inner_table1]
';
set @query_where = ' where 1 = 1 ';
set @query_where = @query_where + ' and [category_path] = ''' + @pi_int_category_id_path + '''
and [user_id] = ''' + @pi_vch_user_id + '''
and [state] != ''3''';
--合并
set @query_select = N'with temp_table AS
(' + @query_select + @query_where + ')
select * from temp_table
where rownumber > ' + convert(varchar(20), @query_start) + '
and rownumber <=' + convert(varchar(20), @query_end);
--总数
set @query_select_count = N'WITH temp_table AS
(
SELECT 1 RowNumber
FROM [dbo].[tbl_inner_table1]
'+ @query_where +' )
select @po_int_total_count = count(1) from temp_table ';
--执行
EXEC SP_EXECUTESQL @query_select_count, N'@po_int_total_count INT OUTPUT ', @po_int_total_count OUTPUT;
--print(@query_select_count);
--print(@query_select);
exec(@query_select);
END