我正在尝试添加分页存储过程的排序功能。 - r! g6 b; e4 h我该怎么办?到目前为止,我已经创造了这个。它工作正常,但当传输时@sort它在参数中不起作用。, _" t, |/ L! t1 Y s
ALTER PROCEDURE [dbo].[sp_Mk] @page INT,@size INT,@sort nvarchar(50) ,@totalrow INT OUTPUTASBEGIN DECLARE @offset INT DECLARE @newsize INT IF(@page=0) begin SET @offset = @page; SET @newsize = @size end ELSE begin SET @offset = @page 1; SET @newsize = @size-1 end -- SET NOCOUNT ON added to prevent extra result sets from SET NOCOUNT ON; WITH OrderedSet AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY @sort DESC) AS 'Index' FROM [dbo].[Mk] ) SELECT * FROM OrderedSet WHERE [Index] BETWEEN @offset AND (@offset @newsize) SET @totalrow = (SELECT COUNT(*) FROM [dbo].[Mk])END 8 z5 J! A. X) k n* w! t 解决方案: 5 ]3 j% V0 G! i7 E 使用动态的方法(可能不是最好的方法)SQL ; r7 d% V9 T9 X$ u! S+ {4 A |) CCREATE PROCEDURE [sp_Mk] @page INT,@size INT,@sort nvarchar(50) ,@totalrow INT OUTPUTASBEGIN DECLARE @offset INT DECLARE @newsize INT DECLARE @sql NVARCHAR(MAX) IF(@page= BEGIN SET @offset = @page SET @newsize = @size END ELSE BEGIN SET @offset = @page*@size SET @newsize = @size- END SET NOCOUNT ON SET @sql = WITH OrderedSet AS ( SELECT *,ROW_NUMBER() OVER (ORDER BY ' @sort ) AS ''Index FROM [dbo].[Mk] SELECT * FROM OrderedSet WHERE [Index] BETWEEN ' CONVERT(NVARCHAR(12),@offset) ' AND ' CONVERT(NVARCHAR(12),(@offset @newsize)) EXECUTE (@sql) SET @totalrow = (SELECT COUNT(*) FROM [Mk])END这是 SQLFiddle 演示