【发布时间】:2012-06-28 10:36:44
【问题描述】:
我需要通过匹配两个表中的 ID 字段,将文本数据与辅助表 tblSecond 中的 Notes 字段连接起来,从而更新表 tblMain 中的 Notes 字段。
我使用的是以下 SQL:
UPDATE tblMain
SET tblMain.Notes = (tblMain.Notes + (SELECT DISTINCT Notes FROM tblSecond
WHERE tblSecond.ID = tblMain.ID))
但我收到以下错误
子查询返回超过 1 个值。
大概是因为 SELECT 语句返回了整个结果集。
我将如何成功执行此操作?
【问题讨论】:
-
我刚刚使用 MERGE
MERGE INTO tblMain USING ( SELECT ID, notes FROM tblSecond ) Second ON (Second.ID = tblMain.ID) WHEN MATCHED THEN UPDATE SET tblMain.Notes = tblMain.Notes + Second.notes再次尝试,但我收到了类似的错误: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. -
我假设在 tblSecond 表中,您可以在 tblMain 中为单个记录有多个注释?换句话说,是否可以将 tblSecond 中的多条记录连接成一条 tblMain 记录?
-
如果 Second 中有两行对应 Main 中的一行,您是否希望将这两行连接到 Main 中?
标签: sql tsql sql-server-2008-r2 subquery