CREATE PROC [dbo].[Procpageselect] @table NVARCHAR(max),-- 輸入參數,表名 @columns NVARCHAR(max),-- 輸入參數,要返回的列 @rows INT,-- 輸入參數,每頁顯示的數據量 @page INT,-- 輸入參數,當前頁面 @orderBy NVARCHAR(max),-- 輸入參數,數據按什麼字段排序,後面加上desc表示倒序 @condition NVARCHAR(max),-- 輸入參數,sql形式的篩選查詢條件 @total INT output -- 輸出參數,知足上訴查詢條件的數據總數 AS BEGIN DECLARE @start INT -- 變量,獲取的當頁數據的起始位置 DECLARE @end INT -- 變量,獲取的當頁數據的結束位置 DECLARE @sql NVARCHAR(max) -- 變量,保存動態生成的sql語句 IF @condition = '' OR @condition IS NULL BEGIN SET @condition = '1=1' END SET @sql = 'select @count = COUNT(*) from ' + @table + ' where ' + @condition EXEC Sp_executesql @sql, N'@count int output', @total output --print(@total) SET @start = @rows * ( @page - 1 ) SET @end = @rows * @page SET @sql = 'with tmp as (select ROW_NUMBER() over(order by ' + @orderBy + ') as [no], ' + @columns + ' from (select * from ' + @table + ' where ' + @condition + ') as a) select * from tmp where [no] > ' + Ltrim(Str(@start)) + ' and [no] <= ' + Ltrim(Str(@end)) --print(@sql) EXEC(@sql) END