Insert / update with subquery
Hi,
i have to insert (if records don't exist) or update (if records already exist) records from table S into table D. S and D have the same structure.
Table S
ID NUMBER, Primary Key,
DESC1 VARCHAR
DESC2 VARCHAR
Table D
ID NUMBER, Primary Key,
DESC1 VARCHAR
DESC2 VARCHAR
Are this statements OK?
INSERT INTO D
( SELECT * FROM S T1 WHERE NOT EXISTS
( SELECT '1' FROM D T2 WHERE T2.ID = T1.ID));
UPDATE D T1
SET (DESC1, DESC2) =
(SELECT DESC1, DECS2
FROM S T2 WHERE T1.ID = T2.ID ) WHERE EXIST
( SELECT '1' FROM S T3 WHERE T1.ID = T3.ID );
Thanks a lot
Depends on exist or not the data in
the destination where id doesn't exists in the source.
SQL> select * from updatable_tab;
ID DESC1 DESC2
1 0 0
1 0 0
1 0 0
1 0 0
2 f f
2 f f
2 f f
2 f f
2 f f
9 rows selected.
SQL> update updatable_tab dst set (desc1, desc2) =
2 (select desc1, desc2 from s where s.id = dst.id)
3 /
9 rows updated.
SQL> select * from updatable_tab;
ID DESC1 DESC2
1 A A
1 A A
1 A A
1 A A
2 B B
2 B B
2 B B
2 B B
2 B B
9 rows selected.
But if you have the row in the destination table
wich does not exists in the source table, it will
nullify your dest1 and dest2.
In this case you should of course:
SQL> select * from updatable_tab;
ID DESC1 DESC2
1 0 0
1 0 0
1 0 0
1 0 0
2 f f
2 f f
2 f f
2 f f
2 f f
3 m m
10 rows selected.
SQL> select * from s;
ID DESC1 DESC2
1 A A
2 B B
SQL> update updatable_tab dst set (desc1, desc2) =
2 (select desc1, desc2 from s where s.id = dst.id)
3 where exists (select null from s where s.id = dst.id)
4 /
9 rows updated.
SQL> select * from updatable_tab;
ID DESC1 DESC2
1 A A
1 A A
1 A A
1 A A
2 B B
2 B B
2 B B
2 B B
2 B B
3 m m
Rgds.
Similar Messages
-
Override INSERT operation with subquery
Hi, OTN.
I have a form to update/insert a table.
While INSERT one of the fields' value should be obtained by a subquery.
SQL operation should look like this:
INSERT INTO table1 (attribA, attribB, attribC)
VALUES (valueA, valueB, ( SELECT max(valueC) + 1
FROM table1
WHERE table1.attribA = valueA
It is necessary to complete insert in a single operation. Not possible to obtain a value with one query and insert it with another. Triggers also shouldn't be used.
So i need to use a subquery. My JDev is 11.1.1.1.0.
How is it done?
ThanksI have problem with detailstamp not working on 11g.
Let us consider : Item , SubItem relationship.
Component : Item VO , SubItemVO , Item can have many subitem.
1.Created ItemVO
2.Create SubItemVO
3.Create View Link based on ItemVo-ItemId that is FK in SubItem table.
4.Created JSF page and Dragged ItemVO from Datacontrol to JSF Pagen as ADF ReadOnly Table.
5.Expanded Item table structure in Structure window and open the detailstamp.
6.Dragged SubItemVO in detailstamp as ADF ReadOnly table.
Expected Result :
1. ItemVO First Row
1.SubItems belonging to ITEMVO First Row
2.SubItems belonging to ITEMVO First Row
2.ItemVO Second Row.
1.SubItems belonging to ITEMVO Second Row
Current Result :
1. ItemVO First Row
1.SubItems belonging to ITEMVO First Row
2.SubItems belonging to ITEMVO First Row
2.ItemVO Second Row.
1.SubItems belonging to ITEMVO First Row
2.SubItems belonging to ITEMVO First Row
Description: Second ItemVO when expanded shows first ItemVO SUBITEMS.
Thanks, -
What is the main difference between Merge Statment(only update) with simple Update statement based on Select query ?
Which one is faster ?There are no vanilla answers to such a question especially when asked by someone who doesn't have time to post version number or DML.
The only honest answer ... build a test environment and test it using EXPLAIN PLAN and SET TIMING ON.
That said: A merge statement should only be used where it is appropriate. -
I want to update a table with data extracted from a xmltype.
But Oracle extracts only the first value from the subquery.
Am I missing something or this is the expected output...
drop table t
create table t(id number, val varchar2(20));
insert into t(id, val) values (1, null)
insert into t(id, val) values (2, null)
select *
from t
ID VAL
1
2
update t set(val) =
(select t.id from dual)
where id = t.id
select *
from t
ID VAL
1 1
2 2
update t set(val) =
(select extractValue(
extract(xmltype('<root>'||
'<node id="1">'||
'<value>1</value>'||
'</node>'||
'<node id="2">'||
'<value>2</value>'||
'</node>'||
'</root>'),
'//root/node[@id='||to_char(t.id)||']'),
'/node/value') from dual)
where id = t.id
select *
from t
ID VAL
1 1
2 1 -- <-- should be 2!Hi,
try this way:
SQL> CREATE TABLE tab AS SELECT 1 id,cast(NULL AS VARCHAR2(20)) val FROM dual UNION ALL
2 SELECT 2,NULL FROM dual;
Table created.
SQL> DESC tab;
Name Null? Type
ID NUMBER
VAL VARCHAR2(20)
SQL>
SQL> SELECT * FROM tab;
ID VAL
1
2
SQL>
SQL> UPDATE tab t
2 SET val=(
3 SELECT
4 extractValue(
5 extract(
6 XMLType('<root>
7 <node id="1">
8 <value>1</value>
9 </node>
10 <node id="2">
11 <value>2</value>
12 </node>
13 </root>')
14 ,'/root/node[@id='||id||']')
15 ,'/node/value') va
16 FROM tab s
17 WHERE t.id=s.id) ;
2 rows updated.
SQL> SELECT * FROM tab;
ID VAL
1 1
2 2
SQL> spool off;btw, you don't need to || every line in xml, and you don't need to do to_char() when using ||
Ants -
JDBC Receiver adapter ( INSERT/UPDATE with SELECT)
Is it possible to have following kind of SQL Statement comming out JDBC Receiver Adatpter. If yes what would be the corresponding XML Document format for this.
UPDATE suppliers
SET supplier_name = ( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
This condition also needs to be applied for Insert condition. Any pointer would be useful.
Thanks,
SamirHi
Refer this links,
http://help.sap.com/saphelp_nw04/helpdata/en/22/b4d13b633f7748b4d34f3191529946/frameset.htm
http://help.sap.com/saphelp_nw04/helpdata/en/b0/676b3c255b1475e10000000a114084/frameset.htm
http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/frameset.htm
http://help.sap.com/saphelp_nw04/helpdata/en/4d/8c103e05df2e4b95cbcc68fed61705/frameset.htm
Regards,
Suryanaryana -
Update with subquery in TopLink ?
I want to activate the user account updating its status to ACTIVE.
UPDATE PujUserEntity as user SET user.status.id = (SELECT status.id from PujUserStatusEntity status WHERE status.tag='ACTIVE') WHERE user.login= :login AND user.email= :email
the error during the deployment on Glassfish (TopLink):
CLI171 Command deploy failed : Deploying application in domain failed;
Exception Description: Syntax error parsing the query [activateUserAccount: UPDATE PujUserEntity as user SET user.status.id = (SELECT status.id from PujUserStatusEntity status WHERE status.tag='ACTIVE') WHERE user.login= :userLogin AND user.email= :userEmail], line 1, column 52: unexpected token [SELECT].
Internal Exception: line 1:52: unexpected token: SELECTAccording to JPA specification you are not allowed to use subquery in that place. In SET part you can only use simple_arithmetic_expression | string_primary | datetime_primary | boolean_primary | enum_primary | simple_entity_expression | NULL (JSR 220 Java Persistence API specification page 104). You should be able to use native query, or find status.id first and then just pass it as parameter.
-
Insert statement with subquery to insert multiple rows
Hi frnds,
Kindly find the below mentioned query and error. Also suggest me to go ahead.
SQL> INSERT INTO FM_TRAN_DOC_NO (TDOC_COMP_CODE,
2 TDOC_TRAN_CODE,
3 TDOC_ACNT_YEAR,
4 TDOC_CUR_NO,
5 TDOC_MAX_NO,
6 TDOC_CAL_YEAR,
7 TDOC_PERIOD,
8 TDOC_DIVN_CODE,
9 TDOC_DEPT_CODE,
10 TDOC_CR_UID,
11 TDOC_CR_DT,
12 TDOC_UPD_UID,
13 TDOC_UPD_DT)
14 SELECT '001',
15 (SELECT DISTINCT TDOC_TRAN_CODE FROM FM_TRAN_DOC_NO
16 '6',
17 '0',
18 '9999',
19 NULL,
20 NULL,
21 NULL,
22 NULL,
23 'AGT',
24 TO_DATE (SYSDATE),
25 NULL,
26 TO_DATE (SYSDATE) FROM DUAL;
(SELECT DISTINCT TDOC_TRAN_CODE FROM FM_TRAN_DOC_NO ),
ERROR at line 15:
ORA-01427: single-row subquery returns more than one rowThis "SELECT DISTINCT TDOC_TRAN_CODE FROM FM_TRAN_DOC_NO" query returns multiple rows. So what is your requirement?
Try the below insert if you want to select from tale FM_TRAN_DOC_NO
INSERT INTO FM_TRAN_DOC_NO (TDOC_TRAN_CODE,
TDOC_COMP_CODE,
TDOC_ACNT_YEAR,
TDOC_CUR_NO,
TDOC_MAX_NO,
TDOC_CAL_YEAR,
TDOC_PERIOD,
TDOC_DIVN_CODE,
TDOC_DEPT_CODE,
TDOC_CR_UID,
TDOC_CR_DT,
TDOC_UPD_UID,
TDOC_UPD_DT)
SELECT DISTINCT
TDOC_TRAN_CODE
'001',
'6',
'0',
'9999',
NULL,
NULL,
NULL,
NULL,
'AGT',
TO_DATE (SYSDATE),
NULL,
TO_DATE (SYSDATE) FROM TDOC_TRAN_CODE;
Message was edited by: 000000 -
Update with exists and subquery
Hi how to pass index to this sql
Table pap ( eqid,seq,histseq,docno,status,value1,value2)
PK(eqid,seq,histseq) and indx (docno)
table pa ( eqid,seq,docno,status,value1,value2)
PK(eqid,seq) and indx (docno)
update pa
set (value1,value2) = (select pap.value1,pap.value2 from pap
where pap.eqid = pa.eqid
and pap.seq = pa.seq
and pap.histseq =1
and pap.docno <> pa.docno
and pap.status = 4 )
where pa.status=1
and exists ( select 1 from pap
where pap.eqid = pa.eqid
and pap.seq = pa.seq
and pap.histseq =1
and pap.docno <> pa.docno
and pap.status =4 )
It is doing fulltable scan on pa and using hash join .
How to write update with subquery method also ?There's nothing wrong with a full scan.
Please read this explanation/example: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9422487749968
If you want more explanation then please follow these guidelines below, so we have sufficient inputs:
[When your query takes too long...|http://forums.oracle.com/forums/thread.jspa?messageID=1812597#1812597]
[How to post a SQL statement tuning request|http://forums.oracle.com/forums/thread.jspa?threadID=863295&tstart=0]
Remember to put the tag befor and after the examples you post.
See http://forums.oracle.com/forums/help.jspa regarding tags. -
BLOB Columns Inserts/Updates ???
Please let me know how SQL*Loader can run updates to just the blob columns without truncation/replace. We want to do incremental updates to the BLOB column without truncation/replace. If this is not possible please let me know any other process which can do this with the best performance we have huge amount of data that needs to be processed. Please let me know .......
e-mail from the developer.
Is there something that we or the DBA’s can do to improve performance on these types of inserts/updates with blobs? Currently we are executing batches of inserts/update to the 5 IMAGE_* tables and those are triggering inserts into the IMAGE*_HISTORY tablesHandle: user01
Status Level: Newbie
Registered: Jun 10, 2004
Total Posts: 252
Total Questions: 28 (24 unresolved)
so many questions & so few answers.
EXTERNAL TABLE is available option
How fast it is depends upon the SQL & design implementation -
How to insert/update Date field in Oracle with java code
Dear All
I have to insert/update a date column while creating a new item, but the problem is i am able to insert/update only date but i need both date and time along with AM/PM.
By using these 3 lines i am able to insert/update only date.
java.util.Date date = new java.util.Date();
long dateLong = date.getTime();
stmtPrep.setDate(33, new java.sql.Date(dateLong));
Below code retrives the date exactly what i need but unable to pass in the statement:
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
java.util.Date d = (Date) new java.util.Date();
String stringdate = formatter.format(d);
String tmpdate = dateFormat();
stmtPrep.setString(33, tmpdate); -- I tried with setObject as well but same error coming.
Error is:
ORA-01830: date format picture ends before converting entire input string
Can u guide me how to get full date time with AM/PM?sasikrishna wrote:
Dear All
I have to insert/update a date column while creating a new item, but the problem is i am able to insert/update only date but i need both date and time along with AM/PM.
By using these 3 lines i am able to insert/update only date.
java.util.Date date = new java.util.Date();
long dateLong = date.getTime();
stmtPrep.setDate(33, new java.sql.Date(dateLong));That's by design. A java.sql.Date object matches an SQL DATE column (which doesn't include a time component). If you want something which matches an SQL TIMESTAMP colum (which includes both date and time components) then you should use a java.sql.Timestamp object. -
INSERT or UPDATE with multiple rows
Hi there!
I want to ask what I should do in the following case: I have to handle mutliple rows of data to insert OR to update into the database.
The first question is about how to decide whether I should take INSERT or UPDATE. I read here in the forum that I could take a SELECT-statement before, and, if it isn't null, I could update the resultset..if it is null I can make an INSERT-statement.
But now I a have multiple rows to update or to insert which I want to handle as a transaction (with a batch), so I don't want to check each row the way I described above. Does anyone has a hint ?
Thanks a lot in advance.This is not a problem with java but rather a problem
with databases in general. The solution generally
depends on the data that is being operated on.
If there is a primary key involved, and most records
were expected to NOT be in the database, then you
could just insert them in blocks (transaction/batch).
Each block would fail when a primary key duplicate.
Then you can process each block as individual
l statements. The ones that fail are done as
inserts.
The reverse of the above is used if you expect most
records to be in the database. Do updates and the
break out the blocks with failures to locate the
inserts.
Keep in mind that queries for keys probably will be
faster, but that requires that your keys are ordered.
If you keys are ordered then you can get a range from
the initial data. Use that to query the database for
keys between that range (only return the keys.)
Using the returned keys you can decide whether each
h record needs to be an update or insert (presort the
data into each group and batch each group for more
speed.)
If the data is really mixed and the database supports
it then you can write a stored proc (MySQL does not)
which decides whether an insert/update is needed.
Finally if you have large amounts of data, bulk
operations especially inserts are better done with
tools supplied by the database vendor. Instead of
using JDBC to do the insert/updates you write the
output to a file and pass the file to the tool. You
might use JDBC (again with the ordered key query) to
decide which operation to do. Although faster for
large sets this is problematic due to the error
handling that you have to add.
Thanks for this, jschell. I look for your answers, because they're on the money and written well. I learn a lot from them. - MOD -
Update column with subquery returning more than one row
Hi Everybody,
Please let me know how to handle this. I am writing update statement in procedure with subquery and it is returning multiple rows. Please help me, how i can handle this :
UPDATE TABLEA A
SET A.ERROR_MESSAGE = (Select B.XERROR_MESSAGE from TABLEB B, TABLEA A WHERE B.id = A.id)
WHERE A.id = (Select B.id from TABLEB B, TABLEA A WHERE B.id = A.id);
(Select B.XERROR_MESSAGE from TABLEB B, TABLEA A WHERE B.id = A.id) --- This subquery is returning more than one rows. How i can handle this in Pl/SQL?
Please let me know. I will be very thankful to you all.
I will really appreciate your replies and comments.
Thank youTry getting rid of tablea in your subqueries. You already have it in the UPDATE statement.
UPDATE TABLEA A
SET A.ERROR_MESSAGE = (Select B.XERROR_MESSAGE
from TABLEB B
WHERE B.id = A.id
WHERE A.id = (Select B.id
from TABLEB B
WHERE B.id = A.id);You can also try a simple MERGE:
merge into tablea a
using tableb b
on (a.id = b.id)
when matched then update
set a.error_message = b.xerror_message; -
Update/Insert Problem with Oracle Warehouse Builder
Hello,
i have update/insert problem with owb.
Situation: I have a source-table called s_account and a target table called w_account_d. In the target table are already data which was filled trough the source table inserts. Now anyone make changes on data on the target table. This changes should now give further on the source table with an update operation. But exactly here is the problem i can´t map back the data to source because that will create a loop.
My idea was to set a trigger but i can´t find this component in owb or is anywhere hidden?
Also i have already seen properties as CDC or conditonal loading in the property inspector of the table, but i have no idea how it works.
Give it other possibilities to modeling this case? or can anyone me explain how i can implement this eventually with CDC?
I look forward for your replies :)Hi
thanks for your answer. I follow your suggestion and have set the constraints of both tables into the database directly.Nevertheless it doesn´t work to begin. In the next step i found by right click on a table the listpoint "configure" - I goes to "unique key" --> creation method and set here follow options: Constraint State = ENABLE, Constraint Validation = Validate. That error message that appears before by the deployment disappears yet. Now i start the job to test if the insert/update process works right. Finally it seems to work - but not really.
My Testscenario
1. Load the data from source table about the staging area to data warehouse table: Check - it works!
2. Change one data record in source table
3. Load the source table with changed data record once again to staging area: Check - it works!
4. Load new staging area table with the changed data record to data warehouse table: Check it works! BUT, BUT i can not recognize if it is insert or update operation, then under the design window by jobs execution windows is reported "rows selected 98", Rows inserted" is empty and "rows updated" is empty. So i think works not correct, then my opinion if it works correct it should show be "rows updated" 1.
What can yet now still be wrong or forgotten? Any ideas?
*By the way think not 98 rows there is not important if you make an update or insert which performance. It is an example table the right tables have million of records.*
I look forward for your answers :) -
ME11 update error : Error during insert EINE with key
HI All,
I am facing the below problem..For one particular user update request is failing in ME11 transaction.Error was found in function module name ME_UPDATE_INFORECORD.I also check if it is number range problem but it is not the case..
Please help me out..
Thanks in advacne.Hi,
The problem is that only one user is getting sporadic failed update messages (since last 3-4 days) when using transaction ME11. The error as recorded in SM13 is "Error during insert EINE with key <Inforecord #> <Pur Org>".
I checked the table EINE for the key mentioned in the above message and found that there is a 2 years old record with the same key. Now, what I do not understand is that while creating a new Inforecord, why does SAP comes up with an old number instead of generating a new one from the number range object. I tried to search on SDN as well as OSS Notes, but could not find any mention to this problem.
And yes, it is an abend message with no short dump...
Thanks,
Gaurav
Edited by: Gaurav Malhotra on Feb 24, 2012 3:08 PM -
Merge update insert into with exception
I m opening a new thread for the same question i had posted earlier....
create Table test(
col1 varchar2(200),
col2 varchar2(200),
col3 varchar2(200),
id varchar2(200),
job_id varchar2(10)
create Table test1(
col1 varchar2(200),
col2 varchar2(200),
col3 varchar2(200),
id varchar2(200),
job_id varchar2(10)
create Table test2(
col1 varchar2(200),
col2 varchar2(200),
col3 varchar2(200),
id varchar2(200),
job_id varchar2(10)
create Table err_tbl(
col1 varchar2(200),
col2 varchar2(200),
col3 varchar2(200),
id varchar2(200),
job_id varchar2(10)
===============================================================
merge into test t
using (select distinct col1, col2, col3,id, job_id
from test1
where job_id = curr_job_id -- cur_job_id is variable which is declared in the procedure to sysdate
union
select distinct col1, col2, col3,id, job_id
from test2
where job_id = curr_job_id --cur_job_id is variable which is declared in the procedure to sysdate
) ss
on (t.id = ss.id
AND t.job_id = ss.job_id)
when matched then update
set t.col1 = ss.col1,
t.col2 = ss.col2,
t.col3 = ss.col3
when not matched then insert into
( t.col1,
t.col2,
t.col3,
t.id,
t.job_id
)Values
( ss.col1,
ss.col2,
ss.col3,
ss.id,
ss.jobid,
exception
when others then
insert into err_tbl (
col1,
col2,
col3,
id,
job_id )
values ( ss.col1,
ss.col2,
ss.col3,
ss.id,
ss.jobid,
Above, all i m trying to do is Updating or inserting into TEST table, and if there is any Duplicate records or any bad records then making use of exception i m INSERTING into ERR_TBL
i get error with the merge insert update code ....
The error i get is --- "ss.col1" column is not allowed here
Any idea guys ????
Hey one more quick question ....Can we use exception in merge insert update block ???user642297 wrote:
I m opening a new thread for the same question i had posted earlier....
Any idea guys ????
Hey one more quick question ....Can we use exception in merge insert update block ???Did you learn nothing nothing from [Your other thread|http://forums.oracle.com/forums/thread.jspa?messageID=3810396�]
(Maybe that's why you never bothered to close it)
It looks like you did learn something, since you ended up saying
Thanks alex...i think i got the answer.....so i cannot use exception handler in merge statement...
Thank you so much!!!What beats me is that yu post the exact same question again, when you already got the answer
?:|
Peter
Maybe you are looking for
-
How many computers can I install Creative Suite CS5.5?
Hi My family has Adobe Creative Site CS5.5. We have three computers and have it installed on 2 of the 3. I was wondering how computers I can install it on. Also, one of the computers are broken. Is there a way I could deactivate the lisense for only
-
Passing a parameter from one class to another class in the same package
Hi. I am trying to pass a parameter from one class to another class with in a package.And i am Getting the variable as null every time.In the code there is two classes. i. BugWatcherAction.java ii.BugWatcherRefreshAction.Java. We have implemented cac
-
Why do I regularly lose my datebook?
This has happened a few times now. I am regularly backing up so I can import it back in, but geez....why is this happening? Thought I fixed it as posted here: http://forums.palm.com/palm/board/message?board.id=windows_hotsync&message.id=50848 But op
-
i have a login screen code written in xsl . I copied the file into tomcat 4.1.12 and it doesn't display page design but instead the source code how to enable it to show the page????
-
Dreamweaver cs3 fresh install from download area not working. Any ideas please?
Hello I need to reinstall dreamweaver CS3 on my Mac. I have tried to do this in the Adobe download area but I am getting a 404. I have the original Dreamweaver CS3 disk but my CD ROM is broken. I have got the serial numbers but the download are won't