0

表格1

-----------------------------
Id      | Batch    |   Qty
-----------------------------
   1       A1         5     
   2       A2         5      
   3       A3         5    
   4       A4         5

表2

-----------------------------
Id     | Batch  | Qty
------------------- ----------
1         A1        6    
2         A2        6    
3         A3        6     
5         A5       10

预期结果

-----------------------------
Id     | Batch  | Qty
-----------------------------    
1         A1       6 (Qty updated)    
2         A2       6 (Qty updated)    
3         A3       6 (Qty updated)    
4         A4       5 (remains as same)    
5         A5       10 (row in table 2)

如何在 SQL Server 中实现这一点?如果有人知道这个数据表操作,请分享..

4

5 回答 5

1

You can use the MERGE query to update Table1 based on Table2:

MERGE INTO Table1 as target
USING Table2 as source
ON (target.id = source.id)
WHEN MATCHED THEN 
    UPDATE SET target.Batch = source.Batch, 
               target.Qty = source.Qty
WHEN NOT MATCHED THEN   
    INSERT (Id, Batch, Qty)
    VALUES (source.Id, source.Batch, source.Qty)
于 2012-06-15T08:04:59.723 回答
0
insert into table3
(
 select * from table1 t1 full outer join table2 t2 on t1.id = t2.id
)
于 2012-06-15T08:06:27.780 回答
0

既然您已经DataTables明确提到,我将向您展示一个LINQ-To-DataSet使用 usingEnumerable.Union和 custom的内存解决方案IEqualityComparer

DataTable tblMerged = Table2.AsEnumerable()
             .Union(Table1.AsEnumerable(), new RowIdComparer())
             .CopyToDataTable();

这是自定义DataRow比较器,以确保将 ID 用作区分:

class RowIdComparer : IEqualityComparer<DataRow>
{
    public bool Equals(DataRow r1, DataRow r2)
    {
        return r1.Field<int>("Id") == r2.Field<int>("Id");
    }

    public int GetHashCode(DataRow row)
    {
        return row.Field<int>("Id").GetHashCode();
    }
}

结果:

Id      Batch   Qty
1         A1    6
2         A2    6
3         A3    6
5         A5    10
4         A4    5
于 2012-06-15T08:37:38.760 回答
0

尝试这个:

Insert Into Table3
Select * From
((Select * from Table1
Except
Select * from Table2) as temp
UNION
(Select * from Table2))
于 2012-06-15T07:57:46.283 回答
0

假设idbatch总是相关的,我们可以有:

SELECT
    COALESCE(t2.id,t1.id) as id,
    COALESCE(t2.batch,t1.batch) as batch,
    COALESCE(t2.qty,t1.qty) as qty
FROM
     Table2 t2
         full outer join
     Table1 t1
         on
             t2.id = t1.id --Or on batch, or both?
于 2012-06-15T08:09:21.290 回答