简体   繁体   中英

Oracle - Merge Statement with INSERT and UPDATE

I have an existing table called TextData with fields TextId and Text. In below statement, I am trying to merge(Insert/Update) some records into this table using -

MERGE INTO maestro.TEXTDATA T
USING ( 
select N'/Common/UserStatusExpired', N'Expired' from dual
union all select N'/Common/UserStatusPwdExpired', N'Pwd Expired' from dual
) AS Source (Id, Txt) ON (T.TEXTID = Source.Id)
WHEN MATCHED THEN
    UPDATE SET TEXT = Source.Txt
WHEN NOT MATCHED THEN
    INSERT (TEXTID, TEXT) VALUES(Source.Id, Source.Txt);

However, getting this error -

missing ON keyword

Can anyone please suggest what I am missing in the Merge statement.

Thank you!

That would be:

MERGE INTO textdata t
USING ( 
    SELECT N'/Common/UserStatusExpired' AS textid, N'Expired' AS text FROM DUAL
    UNION ALL SELECT N'/Common/UserStatusPwdExpired', N'Pwd Expired' FROM DUAL
) s ON (t.textid = s.textid )
WHEN MATCHED THEN
    UPDATE SET text = s.text
WHEN NOT MATCHED THEN
    INSERT (textid, text) VALUES(s.textid, s.text);

Rationale:

  • Oracle does not support AS to define table aliases - you need to remove that keyword

  • The column names must be defined within the subquery

I also aligned the column names between the source and the target table so the query is easier to follow.

I think the (Id, Txt) shouldn't be there as they were.

MERGE INTO maestro.TEXTDATA T
USING ( 
    select N'/Common/UserStatusExpired' id, N'Expired' txt from dual
    union all 
    select N'/Common/UserStatusPwdExpired' id, N'Pwd Expired' txt from dual
    ) AS Source  ON (T.TEXTID = Source.Id)
WHEN MATCHED THEN
     UPDATE SET TEXT = Source.Txt
WHEN NOT MATCHED THEN
     INSERT (TEXTID, TEXT) VALUES(Source.Id, Source.Txt);

The problem is the "as" clause you've specified. Looks like you want to name your columns in the union'd select lists.

MERGE INTO maestro.TEXTDATA T
USING ( 
select N'/Common/UserStatusExpired' id, N'Expired' txt from dual
union all select N'/Common/UserStatusPwdExpired' id, N'Pwd Expired' txt from dual
) source ON (T.TEXTID = Source.Id)
WHEN MATCHED THEN
    UPDATE SET TEXT = Source.Txt
WHEN NOT MATCHED THEN
    INSERT (TEXTID, TEXT) VALUES(Source.Id, Source.Txt)

The railroad diagram shows there is no such "as" clause.

MERGE INTO maestro.TEXTDATA T USING ( select N'/Common/UserStatusExpired' id, N'Expired' txt from dual union all select N'/Common/UserStatusPwdExpired' id, N'Pwd Expired' txt from dual ) source ON (T.TEXTID = Source.Id) WHEN MATCHED THEN UPDATE SET TEXT = Source.Txt WHEN NOT MATCHED THEN INSERT (TEXTID, TEXT) VALUES(Source.Id, Source.Txt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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