【发布时间】:2017-11-21 09:27:47
【问题描述】:
SQL 服务器 2014
我需要用 SourceTable 中的值更新 TargetTable 中的两列
源表
PersonNr | Block | BlockReason |
---------|----------|---------------|
000001 | 1 | abuse |
000001 | 1 | age |
000001 | 0 | memo |
000002 | 1 | age |
000002 | 0 | |
000003 | 0 | |
000003 | 0 | |
000004 | 1 | behaviour |
000005 | 0 | |
目标表
PersonNr | Block | BlockReason |
---------|----------|---------------|
000001 | 0 | |
000001 | 0 | |
000002 | 0 | |
000002 | 0 | |
000004 | 1 | |
000005 | 0 | |
需要结果:
PersonNr | Block | BlockReason |
---------|----------|---------------|
000001 | 1 | abuse |
000001 | 1 | abuse |
000002 | 1 | age |
000002 | 1 | age |
000004 | 1 | behaviour |
000005 | 0 | |
BlockReason Person 1 得到哪个无关紧要,
至于它是来自Block = '1' 的行中的一个。
我已经尝试过这个非常简单的更新:
UPDATE
src
SET
src.Block = '1',
src.BlockReason = targ.BlockReason
FROM
SourceTbl src
INNER JOIN
TargetTable targ
ON
src.PersonNr= targ.PersonNr
WHERE src.Block = '1'
但最终出现了错误的结果行,其中 Block 和 Reason 分别更新:
PersonNr | Block | BlockReason |
---------|----------|---------------|
000001 | 1 | memo |
接下来我试过了:
MERGE INTO TargetTable AS TGT
USING
(
SELECT Block, BlockReason, PersonNr
FROM SourceTbl
GROUP BY Block, BlockReason, PersonNr
) AS SRC
ON
SRC.PersonNr= TGT.PersonNr AND
SRC.Block= '1'
WHEN MATCHED THEN
UPDATE SET TGT.Block= SRC.Block, TGT.BlockReason= SRC.BlockReason;
得到错误
The MERGE statement attempted to UPDATE or DELETE the same row more than once. 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. 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.
有什么帮助吗?非常感谢!真的。完全。
【问题讨论】:
-
您的
UPDATE看起来一般正确,除了源和目标混淆。 (应该是目标,嗯,目标,但仍然是正确的咨询来源的块列) -
@Kaptah 你的表的主键是什么?
标签: sql sql-server merge group-by