简体   繁体   English

如何限制数据集中的行数

[英]How to limit the number of rows in dataset

Code to refer 参考代码

 [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;
             }
          }
      }
 } 

See more at: Link 在以下位置查看更多信息: 链接

The query returns 20 rows and i need to show ten rows alone. 查询返回20行,我需要单独显示10行。 Without any alteration in query is there any possibility to limit the data in dataset.Suggest some ideas 在查询中没有任何更改的情况下,就有可能限制数据集中的数据。

You can try this 你可以试试这个

var rows = ds.Tables[0].AsEnumerable().Take(10);

Now you can also convert these rows into a datatable like this 现在,您还可以将这些行转换成这样的数据表

DataTable limitedTable = rows.CopyToDataTable<DataRow>();

How strict is your requirement to not alter the query? 您对不更改查询的要求有多严格? Can you prepend some text to the query? 您可以在查询中添加一些文字吗?

If so, you can use SET ROWCOUNT . 如果是这样,您可以使用SET ROWCOUNT

Example: 例:

string query = "SET ROWCOUNT 10;"
query += "SELECT * FROM tblCountry";

You can use an overload of Fill that takes the start and end record index. 您可以使用带有开始和结束记录索引的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".

You can find more details here 您可以在这里找到更多详细信息

But like most commenters here, I'd be much more in favour of modifying the query if at all possible 但是像这里的大多数评论者一样, 如果可能的话 ,我会更赞成修改查询

string query = "SELECT TOP 10 FROM tblCountry";

您可以像这样进行查询,仅返回10行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM