简体   繁体   English

SQL Server基于联接2个表的更新和插入

[英]SQL Server update and insert based on joining 2 tables

I have 2 tables which are exactly identical: table1 (a, b, c) and table2 (a, b, c) 我有2个完全相同的表:table1(a,b,c)和table2(a,b,c)

But every night, t2 gets updated and after that update, I want to join these two tables and if the the row exists in t1 , then update t1.b , but if not then insert the row from t2 into t1 . 但是每天晚上, t2都会更新,并且在此更新之后,我想将这两个表连接起来,如果该行存在于t1 ,则更新t1.b ,但是如果不存在,则将t2的行插入到t1

I know this works because it is select 我知道这可行,因为它是精选的

SELECT 
    (CASE
        WHEN t1.a IS NOT NULL 
            THEN t1.b + t2.b
        ELSE t2.b
    END) AS 'total new amount'
FROM
    table1 t1
RIGHT JOIN 
    table2 t2 ON t2.a = t1.a AND t2.c = t1.c

But how can I do the update and insert? 但是,如何进行更新和插入?

UPDATE: 更新:

so I figured I have to use MERGE command 所以我想必须使用MERGE命令

MERGE table1 as t1 
USING table2 as t2 
ON (t1.a = t2.a AND t1.c = t2.c ) 
when MATCHED T
HEN UPDATE SET t1.b = t1.b + t2.b 
when NOT MATCHED 
THEN insert (a,b,c) VALUES (t2.a,t2.b,t2.c);

but now i am getting this error: 但现在我收到此错误:

The MERGE statement attempted to UPDATE or DELETE the same row more than once. MERGE语句尝试多次更新或删除同一行。 This happens when a target row matches more than one source row. 当目标行与多个源行匹配时,就会发生这种情况。 A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. MERGE语句不能多次更新/删除目标表的同一行。 Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows. 优化ON子句以确保目标行最多匹配一个源行,或使用GROUP BY子句对源行进行分组。

what I am doing wrong here? 我在这里做错了什么?

Thanks in advance 提前致谢

But every night, t2 gets updated and after that update, I want to join these two tables and if the the row exists in t1, then update t1.b, but if not then insert the row from t2 into t1. 但是每天晚上,t2都会更新,并且在此更新之后,我想加入这两个表,如果该行存在于t1中,则更新t1.b,但如果不存在,则将t2中的行插入到t1中。

Does anything happen to t1? t1有什么事吗?

If nothing changes in t1 , the simplest way to sync the tables is to just truncate and reload 如果t1没有任何变化,则同步表的最简单方法是截断并重新加载

Depending on how many records in the table and the rate of change, this might be faster or slower than doing an upsert. 根据表中有多少条记录以及更改的速度,这可能比完成更新更快或更慢。

TRUNCATE TABLE T1;

INSERT INTO T1 (Col1,Col2,Col3)
SELECT Col1,Col2,Col3 FROM T2;

Depending on how frequently T1 is used, there are ways to make this transparent to the end user. 根据使用T1的频率,有多种方法可以使T1对最终用户透明。 (ie they'll never see an empty table) (即他们永远不会看到一个空表)

Some methods are: 一些方法是:

MERGE is certainly one way to do an upsert but seperate INSERT and UPDATE statements are often easier to debug and perform better. MERGE当然是进行更新的一种方法,但是单独的INSERTUPDATE语句通常更易于调试和更好地执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM