oracle - Using "WITH" and "UPDATE" statements in the same SQL query -
i have table need update data excel spreadsheet. thinking of query along these lines:
with temp as( (select 'abcd' oldvalue, 'defg' newvalue dual) union (select .....) --about 300 lines of this, copied excel , formatted select statement ) update mytable set name = (select newvalue temp mytable.name = temp.oldvalue)
but oracle doesn't seem having "with" , "update" statement in same query. error saying "missing select keyword". have found out can put temp table definition within select statement, i.e.
set name = (select newvalue ( (select 'abcd' oldvalue, 'defg' newvalue dual) union (select .....) ) temp mytable.name = temp.oldvalue)
but horribly, horribly messy code define table right in middle of query. cringe thinking it. there has better way this. should set global temporary table? or missing simple syntax make work original way?
you can use clause in update; have in right place:
update mytable set name = (with temp as((select 'abcd' oldvalue, 'defg' newvalue dual) union (select .....) --about 300 lines of this, copied excel , formatted select statement ) select newvalue temp mytable.name = temp.oldvalue);
however, you're wanting update rows exist in temp subquery, need additional clause:
update mytable set name = (with temp as((select 'abcd' oldvalue, 'defg' newvalue dual) union (select .....) --about 300 lines of this, copied excel , formatted select statement ) select newvalue temp mytable.name = temp.oldvalue) exists (with temp as((select 'abcd' oldvalue, 'defg' newvalue dual) union (select .....) --about 300 lines of this, copied excel , formatted select statement ) select null temp mytable.name = temp.oldvalue);
alternatively, use merge statement:
merge mytable tgt using (with temp as((select 'abcd' oldvalue, 'defg' newvalue dual) union (select .....) --about 300 lines of this, copied excel , formatted select statement ) select mytable.rowid r_id, temp.newvalue temp inner join mytable on mytable.name = temp.oldvalue) src on (tgt.rowid = src.r_id) when matched update set tgt.name = src.newvalue;
n.b. have join actual table in source query of merge statement because you're trying update column that's being joined on, can't in merge statement - hence i've switched merge join join on mytable.rowid.
you'd have test both statements see 1 performant on yor data.
Comments
Post a Comment