SQL Update,Delete And Insert In Same Time

我的梦境 提交于 2019-12-01 13:14:14

问题


I just curious about something. Let said i have a table which i will update the value, then deleted it and then insert a new 1. It will be pretty easy if i write the coding in such way:

  UPDATE PS_EMAIL_ADDRESSES SET PREF_EMAIL_FLAG='N' WHERE EMPLID IN ('K0G004');

  DELETE  FROM PS_EMAIL_ADDRESSES WHERE EMPLID='K0G004' AND E_ADDR_TYPE='BUSN';

  INSERT INTO PS_EMAIL_ADDRESSES VALUES('K0G004', 'BUSN', 'ABS@GNC.COM.BZ', 'Y');

however, it will be much more easy if using 'update' statement. but My question was, it that possible that done this 3 step in the same time?


回答1:


Quoting Oracle Transaction Statements documentation:

A transaction is a logical, atomic unit of work that contains one or more SQL statements. A transaction groups SQL statements so that they are either all committed, which means they are applied to the database, or all rolled back, which means they are undone from the database. Oracle Database assigns every transaction a unique identifier called a transaction ID.

Also, quoting wikipedia Transaction post:

In computer science, ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably.

Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged.

In your case, you can enclose all three sentences in a single transaction:

COMMIT;         ''This statement ends any existing transaction in the session.
SET TRANSACTION NAME 'my_crazy_update'; ''This statement begins a transaction 
                                         ''and names it sal_update (optional).
 UPDATE PS_EMAIL_ADDRESSES 
    SET PREF_EMAIL_FLAG='N' 
  WHERE EMPLID IN ('K0G004');

 DELETE FROM PS_EMAIL_ADDRESSES 
  WHERE EMPLID='K0G004' AND E_ADDR_TYPE='BUSN';

 INSERT INTO PS_EMAIL_ADDRESSES 
 VALUES('K0G004', 'BUSN', 'ABS@GNC.COM.BZ', 'Y');

COMMIT;

This is the best approach to catch your requirement 'do all sentences at a time'.




回答2:


Use this UPDATE:

UPDATE PS_EMAIL_ADDRESSES
SET
PREF_EMAIL_FLAG = 'N',
E_ADDR_TYPE = 'BUSN',
`column1_name` = 'ABS@SEMBMARINE.COM.SG',
`column2_name` = 'Y'
WHERE EMPLID = 'K0G004';

Where column1_name and column2_name are the column names that you use for those values.




回答3:


Write a stored procedure to do all the operations you want and call that. That would be a single statement!



来源:https://stackoverflow.com/questions/17647923/sql-update-delete-and-insert-in-same-time

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