Monday, February 2, 2009

DML operations based on another table

Copy rows from another table
SQL> create table mytest (tno number(3), tname varchar(20), tloc varchar(10));

Table created.

SQL> insert into mytest
select * from test;

4 rows created.

Note that the 'test' table has the same number of columns as that of 'mytest'. Otherwise you should specify the column names. You should match the number of columns in the INSERT clause with that in the subquery.
SQL> insert into mytest (tno, tname)
select (no, name) from test;

Update two columns:
SQL> update mytest set tname='sample', tloc='CA' where tno=4;

1 row updated.

SQL> select * from mytest;

TNO TNAME TLOC
---------- -------------------- ----------
1 vinay NJ
2 suman NY
3 ravi KY
4 sample CA

SQL> update mytest set
tname=(select tname from mytest where tno=1),
tloc=(select tloc from mytest where tno=2)
where tno=4;

1 row updated.

SQL> select * from mytest;

TNO TNAME TLOC
---------- -------------------- ----------
1 vinay NJ
2 suman NY
3 ravi KY
4 vinay NY

Delete rows based on another table:
SQL> delete from mytest
where tname=(select name from test where tno=3);

1 row deleted.

No comments:

Post a Comment