合并两个表的内容而不复制内容

时间:2012-03-17 04:46:04

标签: sql sql-server sql-server-2008 tsql

我有两个相同的SQL Server表(SOURCEDESTINATION),每个表中都有很多列。我想在表DESTINATION中插入表SOURCE中尚未存在的表DESTINATION行。如果除了timestamp,count列和整数主键之外的所有列都匹配,我定义两行之间的相等性。所以我想在DESTINATION中插入SOURCEDESTINATION中不存在的所有行,忽略count,timestamp和主键列。

我该怎么做?

感谢所有的贡献!我选择使用Merge命令,因为它的结构允许在一个语句中进行更新和插入,我需要单独进行更新。

这是有效的代码:

Merge 
into DESTINATION as D
using  SOURCE as S
on (    
D.Col1 = S.Col1
and D.Col2 = S.Col2
and D.Col3 = S.Col3
)
WHEN MATCHED
 THEN UPDATE SET D.Count = S.Count
 WHEN NOT MATCHED THEN  
        INSERT (Col1, Col2, Col3, Count, timestamp)
        VALUES (S.Col1, S.Col2, S.Col3, S.Count, S.timestamp);

注意:当我第一次写这个问题时,我打电话给表AAABBB。为了清晰起见,我修改了AAASOURCEBBB的名称并将其更改为DESTINATION

3 个答案:

答案 0 :(得分:5)

这样的事情:

INSERT INTO BBB(id, timestamp, mycount, col1, col2, col3, etc.)
SELECT id, timestamp, mycount, col1, col2, col3, etc.
   FROM AAA
   WHERE
       NOT EXISTS(SELECT NULL FROM BBB oldb WHERE
          oldb.col1 = AAA.col1
          AND oldb.col2 = AAA.col2
          AND oldb.col3 = AAA.col3
       )

根据需要向NOT EXISTS子句添加列。

答案 1 :(得分:5)

为此目的使用Select语句,因为Sql Server 2008已过时而不是Select您可以使用Merge语句:

REF:

http://technet.microsoft.com/en-us/library/bb510625.aspx http://weblogs.sqlteam.com/peterl/archive/2007/09/20/Example-of-MERGE-in-SQL-Server-2008.aspx

答案 2 :(得分:1)

使用良好的ol'-fashioned LEFT JOIN的解决方案 - 在下面的示例中注意,只有第一行BBB插入到AAA中,因为只有它在AAA中没有匹配的行。您可以使用表格的实际列替换col1col2

> select * from AAA;
+---------------------+------+------+
| timestamp           | col1 | col2 |
+---------------------+------+------+
| 2012-03-17 08:17:22 |    1 |    1 |
| 2012-03-17 08:17:27 |    1 |    2 |
| 2012-03-17 08:17:30 |    1 |    3 |
| 2012-03-17 08:17:32 |    1 |    4 |
| 2012-03-17 08:17:49 |    2 |    2 |
| 2012-03-17 08:17:52 |    2 |    3 |
| 2012-03-17 08:17:54 |    2 |    4 |
+---------------------+------+------+
7 rows in set (0.00 sec)

> select * from BBB;
+---------------------+------+------+
| timestamp           | col1 | col2 |
+---------------------+------+------+
| 2012-03-17 08:18:16 |    2 |    1 |
| 2012-03-17 08:18:18 |    2 |    2 |
| 2012-03-17 08:18:20 |    2 |    3 |
+---------------------+------+------+
3 rows in set (0.00 sec)

> INSERT INTO AAA
  SELECT BBB.* FROM BBB
  LEFT JOIN AAA
  USING(col1,col2)
  WHERE AAA.timestamp IS NULL;

> select * from AAA;
+---------------------+------+------+
| timestamp           | col1 | col2 |
+---------------------+------+------+
| 2012-03-17 08:17:22 |    1 |    1 |
| 2012-03-17 08:17:27 |    1 |    2 |
| 2012-03-17 08:17:30 |    1 |    3 |
| 2012-03-17 08:17:32 |    1 |    4 |
| 2012-03-17 08:17:49 |    2 |    2 |
| 2012-03-17 08:17:52 |    2 |    3 |
| 2012-03-17 08:17:54 |    2 |    4 |
| 2012-03-17 08:18:16 |    2 |    1 |
+---------------------+------+------+
8 rows in set (0.00 sec)