在c#controller上编写select语句的正确方法是什么?这是我提出的最好的,但我知道它不起作用,因为它在我的第一页上显示所有数据...请帮助
public JsonResult getData(int start, int limit)
{
List<MyItem> items = new List<MyItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyItem item = new MyItem();
item.State = reader[0].ToString();
item.Capital = reader[1].ToString();
items.Add(item);
}
con.Close();
if ((start + limit) > Myitem.Count)
{
limit = Myitem.Count - start;
}
return Json(new { myTable = items }, JsonRequestBehavior.AllowGet);
}
}
答案 0 :(得分:4)
这是我喜欢用于分页的存储过程的模板。
CREATE PROCEDURE [dbo].[StoredProcName]
@page_size INT
, @page_num INT
AS
BEGIN
SET NOCOUNT ON;
; WITH RESULTS AS
(
SELECT *
, ROW_NUMBER() OVER (ORDER BY <order_col> DESC) AS rn
, ROW_NUMBER() OVER (ORDER BY <order_col> ASC) AS rn_reversed
FROM <table>
)
SELECT *
, CAST(rn + rn_reversed - 1 AS INT) AS total_rows
, CAST(CASE (rn + rn_reversed - 1) % @page_size
WHEN 0 THEN (rn + rn_reversed - 1) / @page_size
ELSE ((rn + rn_reversed - 1) / @page_size) + 1
END AS INT) AS total_pages
FROM RESULTS a
WHERE a.rn BETWEEN 1 + ((@page_num - 1) * @page_size) AND @page_num * @page_size
ORDER BY rn ASC
END
您只需要将page_size
和page_num
传递给存储过程,就可以了。
答案 1 :(得分:3)
您可以使用Linq并使用Skip()
和Take()
,如下所示:
public JsonResult getData(int page, int limit)
{
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
{
using (SqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
int start = (page * limit) - limit;
List<MyItem> items = (from DataRow row in dt.Rows
select new MyItem
{
State = row["State"].ToString(),
Capital = row["Capital"].ToString()
}).Skip(start - 1).Take(limit).ToList();
return Json(new { myTable = items }, JsonRequestBehavior.AllowGet);
}
答案 2 :(得分:0)
我使用的基本模板是:
SELECT ROW_NUMBER(), <Rest of your columns>
FROM <Your Tables/Joins>
WHERE ROW_NUMBER() >= (@PageNum * @RowsPerPage)
AND ROW_NUMBER() < (@PageNum+1 * @RowsPerPage)