我有两个相同的SQL Server表(SOURCE
和DESTINATION
),每个表中都有很多列。我想在表DESTINATION
中插入表SOURCE
中尚未存在的表DESTINATION
行。如果除了timestamp,count列和整数主键之外的所有列都匹配,我定义两行之间的相等性。所以我想在DESTINATION
中插入SOURCE
中DESTINATION
中不存在的所有行,忽略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);
注意:当我第一次写这个问题时,我打电话给表AAA
和BBB
。为了清晰起见,我修改了AAA
到SOURCE
和BBB
的名称并将其更改为DESTINATION
答案 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中没有匹配的行。您可以使用表格的实际列替换col1
和col2
。
> 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)