Copy records of one table into another using Update statement
Supposing I have 2 tables test and test1.
Test has columns col1 and col2. and test1 has only one table col1.
select * from test returns:
COL1 COL2
a
b
c
d
e
select * from test1 returns
COL1
p
q
r
s
t
Suppose i want to copy values of test1.col1 to test.col2 so tht final result of
select * from test should be
COL1 COL2
a p
b q
c r
d s
e t
I found a query in the OCP introduction book:
update test set col2=(select col1 from test11)
this works fine only when we have a single record in test1 table but fails otherwise.
how can this be achieved using the update statement ?
SQL> desc test
Name Null? Type
COL1 VARCHAR2(10)
COL2 VARCHAR2(30)
SQL> desc test1
Name Null? Type
COL1 VARCHAR2(10)
SQL> insert into test values ('a','');
1 row created.
SQL> insert into test values ('b','');
1 row created.
SQL> insert into test values ('c','');
1 row created.
SQL> insert into test values ('d','');
1 row created.
SQL> insert into test1 values ('e');
1 row created.
SQL> insert into test1 values ('f');
1 row created.
SQL> insert into test1 values ('g');
1 row created.
SQL> insert into test1 values ('h');
1 row created.
SQL> commit;
Commit complete.
SQL> ed
Wrote file afiedt.buf
1 select a.col1, b.col1, a.rn from
2 (select row_number() over (order by col1) rn, col1 from test) a,
3 (select row_number() over (order by col1) rn, col1 from test1) b
4* where a.rn = b.rn
SQL> /
COL1 COL1 RN
a e 1
b f 2
c g 3
d h 4
SQL> ed
Wrote file afiedt.buf
1 update test set col1 =
2 (
3 select forupd from (
4 select a.col1, b.col1 test1col, a.col1||' '||b.col1 forupd, a.rn from
5 (select row_number() over (order by col1) rn, col1 from test) a,
6 (select row_number() over (order by col1) rn, col1 from test1) b
7 where a.rn = b.rn
8* ) z where z.col1 = test.col1)
SQL> /
4 rows updated.
SQL> commit;
Commit complete.
SQL> select * from test;
COL1 COL2
a e
b f
c g
d h
SQL>
This will work only if you have the same number of lines in COL1 in both tables. If you have different number of lines, then you need to code more at join (outer, inner).
But for complicated cases, please post sample data.
Michael
PS: And supossing that the values are distinct in TEST table. Else update will fail, because more rows will be retrived.
If more values in TEST table in COL1, then you need to assign a row number on TEST also, and in WHERE of query you need to place one more join condition:
something like:
8* ) z where z.col1 = test.col1
and z.rn = test.rn)
SQL> /
But as i said, get more specifications.
Message was edited by:
kjt
Added the PS.
Similar Messages
-
Trigger to copy records from one table to another; ORA-04091:
Hello,
I'm trying to create a trigger that will move data from one table to another.
I have two tables (Trial1, Trial2) Both of them contains the same attributes (code, c_index)
I want to move each new record inserted in (code in Trial1) to (code in Trial2)
This is my trigger:
Create or replace trigger trg_move_to_trial2
After insert on Trial1
for each row
begin
insert into Trial2 (code)
select :new.code from Trial1;
end;It compiled, but when I insert new (code) record into (Trial1) it display this error:
Error report:
SQL Error: ORA-04091: table STU101.TRIAL1 is mutating, trigger/function may not see it
ORA-06512: at "STU101.TRG_MOVE_TO_TRIAL2", line 3
ORA-04088: error during execution of trigger 'STU101.TRG_MOVE_TO_TRIAL2'
04091. 00000 - "table %s.%s is mutating, trigger/function may not see it"
*Cause: A trigger (or a user defined plsql function that is referenced in
this statement) attempted to look at (or modify) a table that was
in the middle of being modified by the statement which fired it.
*Action: Rewrite the trigger (or function) so it does not read that table.I know what does this error mean, but I don't how to fix the error.
I tried to change the (After insert on Trial1) to be (Before insert on Trial1); that worked, but not in the right way. When I insert new value into (code in Trial1) and refreshed Trial2 table, as much as records I have in Trial 2 they will be duplicated. E.g.
Trial2
code
111
222
333when I insert in Trial1
Trial1
code
444
Trial2 will be:
code
111
222
333
444
444
444Can you please tell me how to solve this issue?
Regards,
Edited by: 1002059 on Apr 23, 2013 5:36 PMYou should not select from Trial1 - you have the data already. Just insert that value.
Create or replace trigger trg_move_to_trial2
After insert on Trial1
for each row
begin
insert into Trial2 (code)
values (:new.code);
end; regards,
David -
Automatic copying row from one table into another one
Hi,
I am looking for some help on how to do the following:
I use Number to track my finances. I have two tables - one for my checking account and the other one for my cash account. When I withdraw cash from my checking account I record a transfer or debit transaction in my checking account table (in the type column of this table I enter "transfer" and in the category column of this table I enter "cash account"); Obviously I have to record a matching transaction in my cash account where the category column shall read "checking account". Both records represent one and the same transaction. In order not to enter this transaction twice I would like to "automate" this process so that once I enter the transaction in either of the two table (checking or cash) the matching entry automatically appears in the other table. Is there any way to do this.
Thank you,
EvgenyYou can use Connection#getMetaData() to retrieve information about the tables and the columns of the table.
After all, it is better to gain information about the table first and then issue a query in the form of "INSERT INTO table1 SELECT * FROM table2", including the eventual column selections and/or data conversions at SQL level. -
Inserting data from one table into another table using PL/SQL
HI,
I am trying to insert values from one table into another using PL procedure, the values I want to retrieve from the table riverside1 are charac_id and charac_type and insert these values into another table called riverside2 , the stored procedure zorgs_gorfs(x,y) accepts two parameters which are 2 charac_id's of d characters in riverside1 then using insert statements inserts these characters from riverside1 into riverside2.
CREATE OR REPLACE PROCEDURE zorgs_gorfs(x IN NUMBER, y IN NUMBER) AS
BEGIN
INSERT INTO riverside2
(charac_id)
VALUES
(x);
INSERT INTO riverside2
(charac_id)
VALUES
(y);
END zorgs_gorfs;
/This works but the problem im having is that when I also try to insert the charac_type as well as the charac_id it doesnt work below is the code:
CREATE OR REPLACE PROCEDURE zorgs_gorfs(x IN NUMBER, y IN NUMBER) AS
BEGIN
INSERT INTO riverside2
(charac_id,charac_tye)
VALUES
(Select
charac_id,
charc_type
FROM
riverside1
WHERE
charac_id = x);
END zorgs_gorfs;
/can someone kindly sort me outmodify this sql
INSERT INTO riverside2
(charac_id,charac_tye)
VALUES
(Select
charac_id,
charc_type
FROM
riverside1
WHERE
charac_id = x);as
INSERT INTO riverside2
(charac_id,charac_tye)
VALUES
(Select
charac_id,
charc_type
FROM
riverside1
WHERE
charac_id in ( x,y));But my suggestion would be consider revising your approach. It does not look that good.
Thanks,
karthick. -
T code to Copy Data from one table to another table
Hi,
I want copy all data of one table to its copy table. Anyone knows transaction code to copy data from one table to another table.
Regards,
Jigar Thakkar.Hi
Create a small program.
Extract data from T1 - database table and put it in one internal table - itab1.
loop the itab1 data .............
insert itab1 into tab2. (tab2 - second database table)
endloop.
try this....
hope it works.... -
How to copy data from one table to another (in other database)
Hi. I would like to copy all rows from one table to another (and not use BC4J). Tables can be in various databases. I have already 2 connections and I am able to browse source table using
ResultSet rset = stmt.executeQuery("select ...");
But I would not like to create special insert statement for every row . There will be problems with date formats etc and it will be slow. Can I use retrieved ResultSet somehow ? Maybe with method insertRow, but how, if ResultSet is based on select statement and want to insert into target table? Please point me in the right direction. Thanks.No tools please, it must be common solution. We suceeded in converting our BC4J aplication to PostgreSQL, the MSSQL will be next. So we want to write simple aplication, which could transfer data from our tables between these 3 servers.
-
Loading data from one table to another using cursor
Hi,
I have given the below command to load the data from 1 table to another using cursor.
declare
cursor mycursor IS
SELECT extract_name,from_date,to_date,BETA from temp_table where EXTRACT_NAME='GIFTCARD_DETAILS';
Begin
for mycursor_1 IN mycursor loop
insert into tmp_tab columns(col1,col2,col3,col5) values(mycursor_1.EXTRACT_NAME,mycursor_1.from_date,mycursor_1.to_date,mycursor_1.BETA);
End loop;
commit;
end;
It is working fine.
But I want to hard code some of the columns ( like flags ) which are not there in 1st table and load them into 2nd table.
In db2 we will give commands like
varSqlStatus=`db2 "declare mycurs cursor for select extract_name,from_date,to_date,BETA,'N','Y' from temp_table"`
varSqlStatus=`db2 "load from mycurs of cursor modified by identityignore insert into tmp_tab(col1,col2,col3,col5,col6,col7) nonrecoverable"`
But I want it in oracle 10g, Can any one help me in this.Have you tried either of the two options :
1. Modify the CURSOR itself :
cursor mycursor IS
SELECT extract_name,from_date,to_date,BETA,'N','Y' from temp_table where EXTRACT_NAME='GIFTCARD_DETAILS';2. Modify the INSERT statement itself :
insert into tmp_tab columns(col1,col2,col3,col5,col6,col7) values(mycursor_1.EXTRACT_NAME,mycursor_1.from_date,mycursor_1.to_date,mycursor_1.BETA,'N','Y'); -
How to move records from one table to another?
Is there a way to copy data and column names from one table to another table?
I am trying to copy one production database table onto the development database. we are using Oracle 10g. I tried exporting to an xls file and importing to the other table but this needs to create destination table with the column names. Is there any better approach to achieve this?Hello,
You can create dblink between production and dev and from dev just
*1. create table mytable as select * from mytable@dblink;**2. Use of export/import or datapump*
Example
On prod
exp username/password tables=mytable1,mytable2 file=mytableexport.dmp log=mytableexport.log
On dev
imp username/password tables=mytable1,mytable2 file=mytableexport.dmp log=mytableimport.log*3. Datapump*
http://www.oracle-base.com/articles/10g/OracleDataPump10g.php
*4. Generate csv formatted file and use sqlldr or external*
External Table: http://www.adp-gmbh.ch/ora/misc/ext_table.html
Sqlldr: http://www.psoug.org/reference/sqlloader.html
Regards
Edited by: OrionNet on Feb 13, 2009 6:52 PM -
Create Trigger to insert records from one table to another
I created the below trigger to move data from one table to another after records have been inserted from another table to that table. What I need done is that each time records have been inserted into TEST_TBL, one of these actions codes should be implimented: U-update, N-insert, D-delete and inserted into TEST_TBL1. But each time I run the script, I get bunch of errors. Please see the script below: - Your help will be appreciated.
create or replace
trigger POWER_tr
after update or insert or delete ON test_tbl
for each row
begin
if updating then
insert into test_tbl1
(idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, action_code, date_added
VALUES
(idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, 'U', sysdate);
ELSif INSERTING then
insert insert into test_tbl1
(idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, action_code, date_added
VALUES
(idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, 'N', sysdate);
ELSIF deleting then
insert into test_tbl1
(idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, action_code, date_added
VALUES
(idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, 'D', sysdate);
END IF;
END POWER_tr;
Thank you,
Albert Zaza
Edited by: azaza on Mar 1, 2009 4:14 PMHello
At the end of trigger show errors / and post what errors are you getting exactly?
Here is a simple example for your reference, this will save old values in history table; you can replace it with new values if that's what do you want.
CREATE OR REPLACE TRIGGER TRG_DU
AFTER DELETE OR UPDATE
ON EMPLOYEE REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
DECLARE
BEGIN
IF UPDATING
THEN
INSERT INTO employee_hist
VALUES ('UPDATE',
:OLD.empid,
:OLD.name,
:OLD.deptid);
ELSIF DELETING
THEN
INSERT INTO employee_hist
VALUES ('UPDATE',
:OLD.empid,
:OLD.name,
:OLD.deptid);
END IF;
EXCEPTION
WHEN OTHERS
THEN
-- Consider logging the error and then re-raise
RAISE;
END TRG_DU;
/Regards
Edited by: OrionNet on Mar 1, 2009 7:27 PM -
Copy contents of one table to another
Hi,
Can anyone will give me the code copying the contents of one table to another...
Need an urgetn help..
ThanksThanks for everyones reply...
But here the problem
I to copy the content based on the length of the content
Eg:
If the content key code has 3 characteristics then where ever the last 2 characters are similar i need to copy the rrest content
EG:-
234
236
278
299
288
that means i need to take the last two characteristic and copy the rest data ...
another option
23411
23412
23413
23414
in this i need to check the last 4 characters and copy...
Can any one help..
Another important point is it need to copy in different fields ...
Eg: from where i am copying is FIELD A which has all the data and it need to copy in Field1,2,3,4,5,6,7,8
Thanks -
How to pass selected records from one table to another ?
Hi,
In my view i have designed a table with certain records. I need to pass only specific records of this table to another table which been designed in another view. Can anybody please give sum idea for this.
Rgds
Sudhanshuhi,
Refer the below code:
1. I have selected some data from the table.
2. The selected data is moved to some other internal table.
3. Internal table is further binded to the node in which data is to be shown.
data : lo_nd type ref to if_wd_context_node,
lo_nd1 type ref to if_wd_context_node,
lt_temp type wdr_context_element_set,
wa_temp type ref to if_wd_context_element,
ls_node1 type sflight,
lt_node1 type STANDARD TABLE OF sflight.
lo_nd = wd_context->get_child_node('CN_MAIN'). <CN_MAIN is my node>
CALL METHOD lo_nd->get_selected_elements <here selected data is moved to lt_temp>
RECEIVING
set = lt_temp.
loop at lt_temp INTO wa_temp.
CALL METHOD wa_temp->get_static_attributes
IMPORTING
static_attributes = ls_node1. <Selected data in work area.>
APPEND ls_node1 TO lt_node1. < Data moved to internal Table>
CLEAR ls_node1.
ENDLOOP.
Finally Internal table is binded to the node required.
lo_nd1 = wd_context->get_child_node('CN_MAIN2').
lo_nd1->bind_table( lt_node1 ).
In your case , map this CN_MAIN2 with the Component Controller and from component controller you can access data in your second view also.
I hope it helps.
Thanx.
Saurav. -
Copy data from one Table to another Table
How can I copy data from one Oracle Table to another Oracle Table on a different server? Question 2: How can I clear all of the data in one Table with a single SQL script?
Thanks...Question 1:
I assume you have the privileges. If you don't, ask the DBA to give them to you. Then
1. Login to database_source (It could be either the source or the target. Let's assume it's the source.)
2. Create a database link to database_target: CREATE DATABASE LINK link_to_database_target CONNECT TO myuserid IDENTIFIED BY mypassword USING 'database_target'; Note the single quotes.
3. Copy the table data: INSERT INTO targetowner.mytable@link_to_database_target SELECT * FROM sourceowner.mytable; COMMIT;
Question 2:
You have two options, but you may not have privileges for both.
Option 1:
DELETE FROM tableowner.tablename; COMMIT;
Advantage: Since this is a DML (Data Manipulation Language) statement, you have to commit the transaction. Also, the data will be gone but the table size is NOT changed, so it's ready for accepting replacement data. DML statements can simply be executed not only from SQL scripts, but from PL/SQL scripts as well.
Disadvantage: Slow, because all record deletion is logged, so you can recover from it by issuing a ROLLBACK; instead of the COMMIT; above. The table size is NOT changed, so if you are short of disk space or tablespace space, you have not resolved the issue.
Option 2:
TRUNCATE TABLE tableowner.tablename;
Advantage: Since this is a DDL (Data Definition Language) command, you do NOT have to commit the transaction. (DDL commands automatically commit both before and after their execution.) The table size will be changed back to the initial extent size which is the minimum size a table can have and can only be set when the table is created. If it needs to be changed, the table has to be dropped and recreated with a different initial extent size. The statement execution of this command is not logged, therefore it's much faster then the DELETE.
Disadvantage: No rollback. Being a DDL, this command cannot be executed straight from PL/SQL. If you need to issue this within PL/SQL, you will have to use dynamic SQL. -
How can i transfer some fields from one table to another using a trigger
hi,
i have two tables;sales and accounts.i want in my accounts form to enter salesid which is then validated and if it exists in the sales table, some fields are copied to the accounts table automatically.how do i go about this.thanxhi,
the code u gave me is not running.let me explain in
detail.i have two tables;sales and accounts in my
database (oracle 9i).each have a corresponding form
in the developer window.these tables are linked using
saleid.this id is entered and saved in the
database.when the person is paying in the cash
office,the saleid on an invoice form is entered on
the accounts form.it is supposed to search the sales
table and if the ids match,some records are extracted
from the sales table to the accounts form instead of
the accounts clerk entering the details all over
again.these details will be used to generate a
receipt an then the record on the accounts form is
saved to the database.the contents of the two tables
are:
sales(saleid(pk),startno,endno,quantity,amount,saledat
e)
accounts(receiptno(pk),saleid,startno,endno,quantity,a
mount).
please advice and thanks very muchWhat does it mean "not running" ?
Sure, it is running.
Did you tested my example ?
And it does exactly what you need.
You didn't provided table structures and insert statements,
that's why i showed you the method on 2 emp- tables.
But it is exactly, what do you need.
Change my emp_1 on your sales,
and my emp_2 on your accounts,
and compare the results.
If you cannot directly copy and paste
and say to your teacher / chief "My homework / task is ready"
it doesn't mean, that the solution didn't provided ... -
Copying data from one table to another table thru java
Hi
I have to copy data from table emp in Database A to table emp in Database B. My input would be table name and number of rows to be fetched. these rows i need to insert in table B.
The problem over here is I won't be having any info. of table emp i.e the number of columns it has and their type.
So is their any way i can copy the data from one table to other without having the info abt the number of cols and their type.
TIACross post - http://forum.java.sun.com/thread.jspa?threadID=5169293&messageID=9649839#9649839
-
How to know no of records(in Internal Table) modified after using Modify statement
Hi Experts ,
I am using statement Modify internal table transporting XYZ FIELD.
I just wanted to know how many Records/Count (assuming more then 1 ) get updated just after successful execution of this command.
Is there any system field exist?
if yes please let me know?
Warm Regards,
SantoshHello Santosh,
Try like below and it works for me.
Count will have the number rows changed.
DATA: itab_mara TYPE STANDARD TABLE OF mara,
itab_mara1 TYPE STANDARD TABLE OF mara,
str_mara TYPE mara,
str_mara1 TYPE mara,
diff LIKE IREF-IIND,
count TYPE int2.
SELECT * FROM mara INTO TABLE itab_mara UP TO 10 ROWS.
itab_mara1[] = itab_mara[].
str_mara-lvorm = 'X'.
MODIFY itab_mara FROM str_mara TRANSPORTING lvorm WHERE VPSTA = 'KVB'.
LOOP AT itab_mara INTO str_mara.
READ TABLE itab_mara1 INTO str_mara1 WITH KEY matnr = str_mara-matnr.
CALL FUNCTION 'COMPARE_STRUCTURE_DATA'
EXPORTING
i_ddic_name = 'MARA'
i_rec_old = str_mara
i_rec_new = str_mara1
I_CHECK_MODE = 'Y'
IMPORTING
E_IS_DIFF = diff.
IF diff = 'X'.
count = count + 1.
ENDIF.
ENDLOOP.
WRITE:/ count.
Regards,
Thanga
Maybe you are looking for
-
How getting JAWS 5.0 to read a JDialog
Hi, I have an application that have a few input screen and for each of them I have a report. The report is quiet simple. It is a JDialog with labels, an "OK" button and a "PRINT" button. I have 2 labels for each rows. The first column is the descript
-
Trying to make a log of phone and email contacts with customers. I want to link to the actual email I sent to the customer, like the "show in mail" drag and drop feature in iCal. Thanks
-
How to retrieve all files in a given directory?
Hi all, I am a newbie to Java. I have to retrieve all files in a given directory. The names of the files are not known to me. Only the name of the directory is known. How can I retrieve and read all those files? Gary
-
Configure SAP for server-side trust
Hi all, I am installing BusinessObejcts XI integration for SAP Solution. I need configure SAP for server-side trust. I have read BussinessObjects XI Integration for SAP Solution Installation Guide. In chapter 6, It introduce how to configure SAP Serv
-
I have a JTable in JScrollPane which has about 116000 rows of data. I would like to get a status count of what rows are displayed at a time when I move down the scollPane. This is to keep a running track of rows displayed in status message when movin