Oracle update to split a row into two in safest way with rollback

落爺英雄遲暮 提交于 2020-01-16 04:55:30

问题


I'm working on an existing table that has data similar to:

ID | Name | OldValue | NewValue

these columns have data that is similar to:

14 | name | 'x=>y / zs / z

where the old and new values show a change between values.

What I'd like to do is split these so that this is the result:

15 | name | 'x=>y' | 'x=>s' 16 | name | 'z

I need to safely split this row into two separate rows and then delete the existing data making sure that I'm able to roll back any changes should it hit the fan.

My thoughts are that I should perhaps put all the values into a temporary table where the clauses match what I need. Then use this table to insert the new rows, after which it should be safe to remove the existing rows and the temporary table.
I'm not sure if this is correct and so I was looking for some advice.


回答1:


Do the INSERT and DELETE in single transaction. You can always ROLLBACK the transaction if you see any issues.

To split the rows have a look at :

  • Split single comma delimited string into rows
  • Split comma delimited strings in a table

For example,

Setup

SQL> CREATE TABLE t(str VARCHAR2(100));

Table created.

SQL> INSERT INTO t VALUES ('ID - Name - OldValue - NewValue');

1 row created.

SQL> COMMIT;

Commit complete.

Table Data

SQL> SELECT * FROM t;

STR
-------------------------------
ID - Name - OldValue - NewValue

INSERT after splitting the rows and DELETE the old row

SQL> BEGIN
  2  INSERT INTO t
  3  SELECT trim(regexp_substr(str, '[^-]+', 1, LEVEL)) str
  4          FROM t
  5          CONNECT BY LEVEL <= regexp_count(str, '-')+1;
  6
  7  DELETE FROM t WHERE instr(str, '-') > 0;
  8  END;
  9  /

PL/SQL procedure successfully completed.

Check the table data

SQL> SELECT * FROM t;

STR
---------------------
ID
Name
OldValue
NewValue

Seems good. The rows are now inserted after splitting the delimited string, and then deleted the old row.

ROLLBACK and check the table data

SQL> ROLLBACK;

Rollback complete.

SQL> SELECT * FROM t;

STR
-------------------------------
ID - Name - OldValue - NewValue

So, you are back to the same row.



来源:https://stackoverflow.com/questions/31758797/oracle-update-to-split-a-row-into-two-in-safest-way-with-rollback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!