You might face a situation where you need to interchange the values of 2 columns in an Oracle database table.
E.g. there is a table employee having columns EMPID, FIRST_NAME, LAST_NAME and SALARY. By mistake the values of FIRST_NAME and LAST_NAME have been interchanged. Now you need to bring the data in correct state.
You can think about following few options:
Option-1
1. Alter table employee and add a new column TEMP_NAME to it.
- Update the values of LAST_NAME to TEMP_NAME.
- Update the LAST_NAME with the values of FIRST_NAME.
- Update the FIRST_NAME with the values of TEMP_NAME.
- Drop the column TEMP_NAME.
1. Alter table employee and rename LAST_NAME column to TEMP_NAME.
- Alter table employee and rename column FIRST_NAME to LAST_NAME.
- Alter table employee and rename column TEMP_NAME to FIRST_NAME.
Option-3
Let do it by example:
DROP TABLE EMPLOYEE;
CREATE TBALE EMPLOYEE
(
EMPID NUMBER
,FIRST_NAME VARCHAR2(30)
,LAST_NAME VARCHAR2(30)
,SALARY NUMBER
);
INSERT INTO EMPLOYEE VALUES (1,'Tendulkar','Sachin', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Ganguli','Saurabh', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Pathan','Irfan', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Khan','Jaheer', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Agarkar','Ajit', 10000);
INSERT INTO EMPLOYEE VALUES (1,'Dravid','Rahul', 10000);
SELECT *
FROM EMPLOYEE;
UPDATE EMPLOYEE
SET FIRST_NAME = LAST_NAME
,LAST_NAME = FIRST_NAME;
SELECT *
FROM EMPLOYEE;
The update statement above solves the purpose. Is not it simple? But how does it work??
For any DML (Insert, Update or Delete) oracle internally fires the row level triggers. You can read more about triggers at
As you know in row level triggers the values of each column is stored in :OLD and :NEW parameters. For the above UPDATE statement oracle stores the old values of FIRAT_NAME and LAST_NAME in :OLD.FIRST_NAME and :OLD.LAST_NAME parameters respectively and then update FIRST_NAME with :OLD.LAST_NAME and LAST_NAME with :OLD.FIRST_NAME.
No comments:
Post a Comment