【问题标题】:Keep adding query results to datatable继续将查询结果添加到数据表
【发布时间】:2016-01-02 18:42:12
【问题描述】:

我有一个包含两个表的数据集。 Table[0] 被多行填充。然后我需要迭代这些行并为每一行运行另一个查询并将这些结果填充到表 [1]。在循环中用多行填充数据集的正确方法是什么?我所在位置的缩写代码示例:

 DataSet ds = new DataSet();
    sql = myquery1;
    SqlDataAdapter da = new SqlDataAdapter(sql, conn);
    da.Fill(ds, "Products");

foreach (DataRow dr in ds.Tables[0].Rows)
{
   productID = ds.Tables[0].Rows[0]["ProductID"].ToString();

   if (productID != String.Empty)
   {
      sql = String.Empty;
      sql = myquery2 where productID = 'xxxxx'
      da = new SqlDataAdapter(sql, conn);
      da.Fill(ds, "ProductProperties");
    }
}

这会在第一个循环中填充“ProductProperties”数据表,但不会添加未来的结果。继续向数据表添加多个结果集的正确方法是什么?

【问题讨论】:

    标签: c# datatable dataset sqldataadapter


    【解决方案1】:

    你做错了。您只需要一个查询来填充子表。例如

    Dim ds As New DataSet
    
    Using connection As New SqlConnection("connection string here"),
          parentAdapter As New SqlDataAdapter("SELECT * FROM ParentTable",
                                              connection),
          childAdapter As New SqlDataAdapter("SELECT * FROM ChildTable WHERE ParentID IN (SELECT ParentID FROM ParentTable)",
                                             connection)
        connection.Open()
    
        parentAdapter.Fill(ds, "Parent")
        parentAdapter.Fill(ds, "Child")
    End Using
    

    您需要做的就是将父查询复制为子表的子查询。如果需要,您甚至可以将两个查询放在一个数据适配器中。关键是不需要遍历父记录并为每个记录执行单独的查询。

    【讨论】:

      【解决方案2】:

      你的查询应该返回两个记录集

      SELECT ProductId, Name
      FROM Products
      
      SELECT ProductId, Property1, Property2
      FROM ProductProperties
      

      然后您可以将上述查询中的数据读取到 DataSet 中,如下所示。因此,您将在 DataSet 中获得两个表,其中包含来自上述查询的两个记录集的结果

      using (SqlConnection con = new System.Data.SqlClient.SqlConnection(connString))
      {
         using (SqlCommand cmd = new SqlCommand())
         {
          cmd.CommandText = "query";
             cmd.Connection = con;
      
          con.Open();
      
          SqlDataAdapter adapter = new SqlDataAdapter(cmd);
      
          DataSet ds = new DataSet();
          adapter.Fill(ds);
          con.Close();
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        • 1970-01-01
        • 2021-07-23
        • 2016-04-04
        相关资源
        最近更新 更多