天天看點

分頁功能存儲過程,Delphi 和 .NET應用

=============== SQL 中的存儲過程 ====================

CREATE procedure splitPage
@sqlstr nvarchar(4000), --查詢字元串 
@currentpage int, --第N頁 
@pagesize int --每頁行數 
as 
set nocount on 
declare @P1 int, --P1是遊标的id 
@rowcount int 
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@[email protected] output 
select ceiling(1.0*@rowcount/@pagesize) as pageCount,@rowcount as recCount,@currentpage as curPage
set @currentpage=(@currentpage-1)*@pagesize+1 
exec sp_cursorfetch @P1,16,@currentpage,@pagesize 
exec sp_cursorclose @P1 
set nocount off
GO
           

=============== Delphi 中應用存儲過程 ===================

var myDataSet: _Recordset; 
begin
ADODataSet1.Close ;
ADOStoredProc1.Close;
ADOStoredProc1.Parameters.ParamByName('@sqlstr').Value :='select * from History49'; //SQL
ADOStoredProc1.Parameters.ParamByName('@currentpage').Value := 2; //取得第2頁
ADOStoredProc1.Parameters.ParamByName('@pagesize').Value := 20; //每頁行數
ADOStoredProc1.ExecProc;
ADOStoredProc1.Open;
// 第 一個記錄集
myDataSet := lhgDM.asProcLS.NextRecordset(0);
if myDataSet = nil then exit;
// 第 2 個記錄集 (頁數 ,記錄數資訊)
myDataSet := lhgDM.asProcLS.NextRecordset(1);
if myDataSet = nil then exit;
ADODataSet1.Recordset := myDataSet ;
ADODataSet1.First ;
pageCount := ADODataSet1.FieldByName('pageCount').AsInteger; // 總頁數
recCount := ADODataSet1.FieldByName('recCount').AsInteger; //總記錄數
// 第 3 個記錄集 目前SQL請求第N頁的記錄
myDataSet := lhgDM.asProcLS.NextRecordset(2);
if myDataSet = nil then exit;
ADODataSet1.Recordset := myDataSet ;
ADODataSet1.first;
while not ADODataSet1.EOF do begin
...
end;
end;
           

=============== .NET(c#) 中應用存儲過程 ===================

public DataView createDataViewWithPage(string strSQL,string dsName,int currentPage,
int pageRows,ref int pageCount,ref int RowCount)
{
if (currentPage<=0) return null;
if (SQLConn==null) SQLConn = setConn(SQLConnStr);
if (SQLConn==null) return null;
SqlCommand myCmd = new SqlCommand();
myCmd.CommandText = "splitPage" ; //存儲過程名稱
myCmd.CommandType = CommandType.StoredProcedure ;
myCmd.Parameters.Add("@sqlstr", SqlDbType.VarChar,4000).Value = strSQL;
myCmd.Parameters.Add("@currentpage", SqlDbType.Int).Value = currentPage;
myCmd.Parameters.Add("@pagesize", SqlDbType.Int).Value = pageRows;
myCmd.Connection = SQLConn;
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = myCmd;
DataSet ds = new DataSet();
sqlDA.Fill(ds,dsName);
pageCount = Convert.ToInt32(ds.Tables[1].DefaultView[0]["pageCount"].ToString()); //總有頁數
RowCount = Convert.ToInt32(ds.Tables[1].DefaultView[0]["recCount"].ToString()); //總記錄數
//curPage = Convert.ToInt32(ds.Tables[1].DefaultView[0]["curPage"].ToString()); //目前頁
return ds.Tables[2].DefaultView;// ds.Tables[dsName].DefaultView ;
}