0
update table set column1 = value where column2 = match_value and rownum =1

匹配多行时只能更新单行,但是在'Merge into'语句中匹配多行时如何只更新单行;

    merge into table1
using table2
on (table1.column1 = table2.column1)
when mateched then
update
set column2 = table2.column2;
4

1 回答 1

2

这对我有用:

merge into table1
using table2
on (table1.column1 = table2.column1 and rownum = 1)
when mateched then
update
set column2 = table2.column2;

例如(Oracle 11gR2):

CREATE TABLE TST_MERGE
       (ID NUMBER,
       VAL NUMBER);

INSERT INTO TST_MERGE (ID, VAL)
VALUES (1,1);
INSERT INTO TST_MERGE (ID, VAL)
VALUES (1,2);
INSERT INTO TST_MERGE (ID, VAL)
VALUES (2,2);
INSERT INTO TST_MERGE (ID, VAL)
VALUES (2,3);

CREATE TABLE TST_MERGE1
       (ID NUMBER,
       VAL NUMBER);

INSERT INTO TST_MERGE1 (ID, VAL)
VALUES (1,-1);
INSERT INTO TST_MERGE1 (ID, VAL)
VALUES (2,-1);

MERGE INTO TST_MERGE a
USING (SELECT * FROM TST_MERGE1
WHERE ID = 1) b
ON (a.id = b.id AND rownum = 1)
WHEN MATCHED THEN UPDATE
SET a.val = b.val;

MERGE INTO TST_MERGE a
USING (SELECT * FROM TST_MERGE1
WHERE ID = 2) b
ON (a.id = b.id AND rownum = 1)
WHEN MATCHED THEN UPDATE
SET a.val = b.val;

SELECT * FROM TST_MERGE;

ID      VAL
1   -1
1   2
2   -1
2   3
于 2013-09-24T12:04:20.133 回答