如何使用SQL Server中的存储过程合并第三个表中的两个DataTable?

时间:2012-06-15 07:53:15

标签: sql sql-server algorithm stored-procedures

表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中实现此目的?如果有人知道这个数据表操作请分享..

5 个答案:

答案 0 :(得分:1)

您可以使用MERGE查询根据Table2更新Table1:

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)

答案 1 :(得分:0)

试试这个:

Insert Into Table3
Select * From
((Select * from Table1
Except
Select * from Table2) as temp
UNION
(Select * from Table2))

答案 2 :(得分:0)

insert into table3
(
 select * from table1 t1 full outer join table2 t2 on t1.id = t2.id
)

答案 3 :(得分: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?

答案 4 :(得分:0)

由于您明确提到DataTables,我将使用Enumerable.Union和自定义LINQ-To-DataSet向您展示内存解决方案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