SQLServer數據庫分頁查詢


出表A中的第31條到40條記錄(表A以自動增長的ID做主鍵,注意ID可能是不連續的
--事先刪除了ID 為33的數據
 
--第一種
select top 10 ID from T where ID not in(select top 30 ID from T ORDER BY ID ASC)ORDER BY ID
 例:select top (@pageSize) * from table where id not in (select top ((@pageIndex-1)*@pageSize) id from table order by id ) order by id 
--第二種
SELECT * FROM (select top 10 * FROM( select top 40 * from T order by ID asc)TT order by TT.ID DESC)TTT order by TTT.ID asc
--第三種
select * from T where T.ID in( select top 10 ID FROM(select top 40 ID from T order by T.ID asc)TT order by TT.ID desc) order by ID
--第四種
select * from( select ROW_NUMBER() over(order by ID)TT FROM T)TTT WHERE TTT.TT between 30 and 40
 
 
分頁存儲過程的寫法:
create Proc P_LoadPageData
  --參數
  @pageSize int,
  @pageInderx int,
  @total int out
as
  --代碼
  select top (@pageSize) * from table where id not in
   (
    select top ((@pageIndex-1)*@pageSize) id from table order by id
   )  order by id 
 
  select total = count('a') from table
  select total
 
--測試存儲過程 
  declare @total int
  exec P_LoadPageData 3,5,@total out
  print @total
  select @total
 
//以下是在.net中調中存儲過程
 

public System.Collections.Generic.List<Model.HKSJ_Main> LoadPageData(int pageIndex, int pageSize, out int total)
{
DataSet ds = new DataSet();

SqlParameter totalParameter = new SqlParameter("@total", SqlDbType.Int);
totalParameter.Direction = ParameterDirection.Output;
//DbHelperSQL.RunProcedure()


//如果用了輸出參數,那么就用SqlDataAdapter就可以了,用sqlDataReader時候拿不到輸出參數的值。
using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
{
//conn.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("P_LoadPageData", conn))
{
adapter.SelectCommand.Parameters.Add(new SqlParameter("@pageIndex", pageIndex));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@pageSize", pageSize));

adapter.SelectCommand.CommandType = CommandType.StoredProcedure;

//輸出參數的用法
adapter.SelectCommand.Parameters.Add(totalParameter);

adapter.Fill(ds);
}
}
total = (int)totalParameter.Value;//拿到輸出參數的值

return this.DataTableToList(ds.Tables[0]);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM