SQL 存储过程 分页查询
ALTER PROCEDURE [dbo].[gzProc_TablePage] @tablename varchar(MAX),--表名 @selcolumn varchar(MAX),--查询字段 @where varchar(MAX),--where条件 @sortcolumn varchar(MAX),--排序字段 @pagecount int,--每页记录数 @pageindex int--页号 AS BEGIN /*************************************************** -- 功能:分页查询 -- 作者:GarsonZhang -- 时间:2016年3月21日10:19:07 -- 备注: -- 测试: ***************************************************/ declare @beginrow int declare @endrow int set @beginrow=0 set @endrow=0 set @beginrow=(@pageindex-1)*@pagecount+1 set @endrow=@pageindex*@pagecount declare @sqlstr VARCHAR(MAX) set @sqlstr='with table1 as(select '+ @selcolumn +',ROW_NUMBER() OVER(ORDER BY '+ @sortcolumn+' ) AS ROW'+ ' FROM '+@tablename+' WHERE '+@where+') '+' SELECT '+@selcolumn+' FROM TABLE1 WHERE ROW BETWEEN '+cast(@beginrow as nvarchar )+' and '+cast(@endrow as nvarchar) PRINT @sqlstr --set @sqlstr=@sqlstr +' SELECT '+ @selcolumn +' FROM TABLE1 WHERE ROW BETWEEN '+cast(@beginrow as nvarchar )+' and '+cast(@endrow as nvarchar) --set @sqlstr=@sqlstr +' SELECT '+@selcolumn+' FROM TABLE1 WHERE ROW BETWEEN '+cast(@beginrow as nvarchar )+' and '+cast(@endrow as nvarchar) --PRINT @sqlstr exec(@sqlstr) END
SELECT [Extent1].[RoleId] AS [RoleId], [Extent1].[OrganizeId] AS [OrganizeId], [Extent1].[Category] AS [Category], [Extent1].[EnCode] AS [EnCode], [Extent1].[FullName] AS [FullName], [Extent1].[IsPublic] AS [IsPublic], [Extent1].[OverdueTime] AS [OverdueTime], [Extent1].[SortCode] AS [SortCode], [Extent1].[DeleteMark] AS [DeleteMark], [Extent1].[EnabledMark] AS [EnabledMark], [Extent1].[Description] AS [Description], [Extent1].[CreateDate] AS [CreateDate], [Extent1].[CreateUserId] AS [CreateUserId], [Extent1].[CreateUserName] AS [CreateUserName], [Extent1].[ModifyDate] AS [ModifyDate], [Extent1].[ModifyUserId] AS [ModifyUserId], [Extent1].[ModifyUserName] AS [ModifyUserName] FROM [dbo].[Base_Role] AS [Extent1] WHERE 3 = [Extent1].[Category] ORDER BY [Extent1].[CreateDate] DESC OFFSET 0 ROWS FETCH NEXT 30 ROWS ONLY
其他种方式:offset fetch next方式(SQL2012以上的版本才支持:推荐使用 )
select * from ArtistModels order by ArtistId offset 4 rows fetch next 5 rows only
--order by ArtistId offset 页数 rows fetch next 条数 rows only ----
执行结果是:
慎于行,敏于思!GGGGGG