2017-09-22 37 views
-1

我有兩個數據表,每個數據表有不同的70-80列。我想通過比較兩個在c#中的主鍵後匹配的其他數據表字段值來更新一個數據表字段的值。在比較兩個主鍵後,更新一個數據表

假設我有一個數據表dt1包含行和60列。

我有另一個數據表dt2包含行和70列。 和10列dt1與dt2匹配。 30行dt1與dt2匹配。 所以我想比較兩個數據表的主關鍵字,以及之後是否匹配從dt1到dt2的更新列值。

回答

0

以下是您的答案,考慮dt1 = Customer和dt2 = Order,CustomerId存在於兩個數據表中,並且我還使用LINQ擴展方法加入了它們,最後從兩個數據表中選擇列。謝謝。

static void Main(string[] args) 
    { 
     DataTable dt1 = new DataTable(); //dt1=Customer 
     dt1.Columns.Add("CustomerId", typeof(int)); 
     dt1.Columns.Add("Name", typeof(string)); 

     dt1.Rows.Add(1, "Customer A"); 
     dt1.Rows.Add(2, "Customer B"); 
     dt1.Rows.Add(3, "Customer C"); 

     DataTable dt2 = new DataTable(); //dt2=Order 
     dt2.Columns.Add("OrderId", typeof(int)); 
     dt2.Columns.Add("CustomerId", typeof(int)); //Fk 
     dt2.Columns.Add("OrderDate", typeof(DateTime)); 
     dt2.Columns.Add("OrderAmount", typeof(double)); 

     dt2.Rows.Add(1, 1,DateTime.Now,15000); 
     dt2.Rows.Add(2, 1, DateTime.Now,10000); 
     dt2.Rows.Add(3, 2, DateTime.Now,25000); 

     var result = dt2.AsEnumerable() 
      .Join(dt1.AsEnumerable(), 
      x => x.Field<int>("CustomerId"), //Order(CustomerId) FK 
      y => y.Field<int>("CustomerId"), //Customer Id(Pk) 
      (x, y) => new { dt2 = x, dt1 = y }) //dt2=Order, dt1=Customer 
      .Select(x => new 
      { 
       OrderId = x.dt2.Field<int>("OrderId"), 
       CustomerId = x.dt1.Field<int>("CustomerId"), 
       Name = x.dt1.Field<string>("Name"), 
       OrderDate = x.dt2.Field<DateTime>("OrderDate"), 
       OrderAmount = x.dt2.Field<double>("OrderAmount"), 
      }); 

     foreach (var item in result) 
     { 
      Console.WriteLine("Order Id: {0}, CustomerId: {1}, Name: {2}, OrderDate: {3}, OrderAmount: {4}", 
       item.OrderId,item.CustomerId,item.Name,item.OrderDate,item.OrderAmount); 
     }   

     Console.ReadKey(); 
    } 
0

你需要引用的表單獨不幸。

UPDATE tbl1 SET 
col2c=(SELECT colc2 FROM tbl2 WHERE tbl2_pk=tbl1.tbl1_pk), 
col4e=(SELECT cole4 FROM tbl2 WHERE tbl2_pk=tbl1.tbl1_pk) 
WHERE test.tbl1.tbl1_pk=(SELECT tbl2_pk FROM tbl2 WHERE tbl1_pk=tbl2_pk) 

Link to see results in table pre and post execution