问题
表1:
| KeyColumn | DataColumn1 | DataColumn2|
01 0.1 0.2
02 0.13 0.41
表2:
| anotherKey | DataColumn1 | DataColumn2|
A1 .15 1.2
A2 .25 23.1
表3:
|KeyColumn| anotherKey |
01 A1
02 A1
给定一个键(A1或A2),我需要使用表2中的相应值更新表1中的DataColumn1和DataColumn2列。
因此table1可以更新x行,如上面的数据所示。如果我想更新A1,则应更新01和02行
(因此table1中的值对于datacolumn1为0.15,对于01和02键上的datacolumn2为1.2)
到目前为止我尝试了什么:
MERGE table1
USING (SELECT *
FROM table2
LEFT OUTER JOIN table3
on table2.anotherKey = table3.anotherKey
WHERE table2.anotherKey = 'A1') tmpTable
ON
table1.keyColumn = tmpTable.keyColumn
WHEN MATCHED THEN
UPDATE
SET table1.DataColumn1 = tmpTable.DataColumn1
,table1.DataColumn2 = tmpTable.DataColumn2;
问题:
和错误:
Msg 102,Level 15,State 1,Line 1 'a'附近的语法不正确。 Msg 102,Level 15,State 1,Line 12 'd'附近的语法不正确。
答案 0 :(得分:31)
您的查询将给出错误
Msg 8156, Level 16, State 1, Line 59
The column 'AnotherKey' was specified multiple times for 'tmpTable'.
这是因为您在using子句中使用了*
,而AnotherKey
是table2
和table3
的一部分。
指定所需的列。此外,由于您在keycolumn
子句中使用on
,因此无需使用外连接。
MERGE table1
USING (SELECT table3.keycolumn,
table2.DataColumn1,
table2.DataColumn2
FROM table2
INNER JOIN table3
ON table2.anotherKey = table3.anotherKey
WHERE table2.anotherKey = 'A1') tmpTable
ON
table1.keyColumn = tmpTable.keyColumn
WHEN MATCHED THEN
UPDATE
SET table1.DataColumn1 = tmpTable.DataColumn1
,table1.DataColumn2 = tmpTable.DataColumn2;
<强>更新强>
发布实际错误总是有帮助的。
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'a'. Msg 102, Level 15, State 1, Line 12 Incorrect syntax near 'd'.
看起来你在SQL Server 2005上。合并可以从SQL Server 2008获得。
您可以使用select @@version
检查SQL Server版本。