T-SQL存储过程:ROW_NUMBER()分页
CREATE PROCEDURE GET_MSGLIST
@PageIndex int=1,
@PageSize int=20,
@OrderField nvarchar(20),
@IsDesc int=0
AS
DECLARE @sql nvarchar(4000),@HighSide int,@LowSide int,@OrderMark nvarchar(5);
BEGIN
IF(@IsDesc=1)
BEGIN
SET @OrderMark='DESC';
END;
ELSE
BEGIN
SET @OrderMark='ASC';
END;
IF(@PageIndex=1)
BEGIN
SET @LowSide=1;
SET @HighSide=@PageSize;
END;
ELSE
BEGIN
SET @LowSide=@PageIndex*@PageSize-@PageSize;
SET @HighSide=@PageIndex*@PageSize;
END;
SET @sql='select c.* from (select top '+cast(@HighSide as nvarchar)+
' ROW_NUMBER() OVER(ORDER BY '+@OrderField+' '+@OrderMark+') AS RowID,ML.*,MT.[Name],MT.Description '+
'FROM MsgList ML INNER JOIN MsgType MT ON ML.TID=MT.ID) c '+
'WHERE RowID BETWEEN '+cast(@LowSide as nvarchar) +' AND '+cast(@HighSide as nvarchar);
PRINT(@sql);
EXEC(@sql);
END
@PageIndex int=1,
@PageSize int=20,
@OrderField nvarchar(20),
@IsDesc int=0
AS
DECLARE @sql nvarchar(4000),@HighSide int,@LowSide int,@OrderMark nvarchar(5);
BEGIN
IF(@IsDesc=1)
BEGIN
SET @OrderMark='DESC';
END;
ELSE
BEGIN
SET @OrderMark='ASC';
END;
IF(@PageIndex=1)
BEGIN
SET @LowSide=1;
SET @HighSide=@PageSize;
END;
ELSE
BEGIN
SET @LowSide=@PageIndex*@PageSize-@PageSize;
SET @HighSide=@PageIndex*@PageSize;
END;
SET @sql='select c.* from (select top '+cast(@HighSide as nvarchar)+
' ROW_NUMBER() OVER(ORDER BY '+@OrderField+' '+@OrderMark+') AS RowID,ML.*,MT.[Name],MT.Description '+
'FROM MsgList ML INNER JOIN MsgType MT ON ML.TID=MT.ID) c '+
'WHERE RowID BETWEEN '+cast(@LowSide as nvarchar) +' AND '+cast(@HighSide as nvarchar);
PRINT(@sql);
EXEC(@sql);
END