[英]How to limit the number of rows in dataset
参考代码
[WebMethod]
public static string GetData()
{
string query = "SELECT * FROM tblCountry";
SqlCommand cmd = new SqlCommand(query);
return GetData(cmd).GetXml();
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = @"Data Source=.\sqlExpress;Initial Catalog=dbTest;Integrated Security=SSPI; pooling=false";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
在以下位置查看更多信息: 链接
查询返回20行,我需要单独显示10行。 在查询中没有任何更改的情况下,就有可能限制数据集中的数据。
你可以试试这个
var rows = ds.Tables[0].AsEnumerable().Take(10);
现在,您还可以将这些行转换成这样的数据表
DataTable limitedTable = rows.CopyToDataTable<DataRow>();
您对不更改查询的要求有多严格? 您可以在查询中添加一些文字吗?
如果是这样,您可以使用SET ROWCOUNT 。
例:
string query = "SET ROWCOUNT 10;"
query += "SELECT * FROM tblCountry";
您可以使用带有开始和结束记录索引的Fill
重载。
var ds = new DataSet; //using means the DataSet will go out of scope so you can't return it!
sda.Fill(1, 10, ds.Tables.Add("MyTable"));
return ds; //it now contains a table called "MyTable".
您可以在这里找到更多详细信息
但是像这里的大多数评论者一样, 如果可能的话 ,我会更赞成修改查询
string query = "SELECT TOP 10 FROM tblCountry";
您可以像这样进行查询,仅返回10行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.