Nested Subselect in UPDATE statement
Hi everybody,
I have the following problem: There are two tables FOO and BAR that both have columns X and Y and a primary key. I want to fill the values X and Y of FOO with the values X and Y from BAR where FOO.key = BAR.key . There may be multiple rows from BAR with the same key so I simply select the first one. The query would look like
UPDATE foo f
SET ( x, y ) = ( SELECT *
FROM ( SELECT b.x, b.y
FROM bar b
WHERE f.key = b.key )
WHERE ROWNUM = 1 );However, this doesn't work because the alias F is not known inside the nested subquery. If I remove the outer subquery ( the one with ROWNUM=1 ) it works fine. But I need to limit the result to a single row ( in the real application I sort the innermost query by date ). Why does Oracle forget the meaning of alias F within the nested subquery?
Pat
Hi, Pat,
A subquery can be correlated only to its immediate parent query, not its grandparent.
You can get the results you want using MERGE instead of UPDATE.
You can also get the same results with only one sub-query, something like this:
UPDATE foo f
SET ( x, y ) = ( SELECT MAX (x) KEEP (DENSE_RANK LAST ORDER BY a_date)
, MAX (y) KEEP (DENSE_RANK LAST ORDER BY a_date)
FROM bar
WHERE key = f.key
);I suspect MERGE will be more efficient.
Edited by: Frank Kulash on Mar 9, 2010 11:02 AM
Similar Messages
-
Update statement with nested selects and alias usage
Hello, we are trying to build an update statement like this...
update table1 t1
set attr1 = ( select someattr
from (nested select 1) as aux1
(nested select 2 (nested select 2.1 + nested select 2.2)) ) as aux2
where some_join_clauses
where t1.attr2 = 123
and t1.attr3 = 'abc'
Alias t1 shound be known at the level of nested select 1,2 and 2.1, 2.2? We are receiving an error message saying that t1.someattr is an invalid identifier. Can you help? Thanks!mauramos wrote:
Hello, we are trying to build an update statement like this...
update table1 t1
set attr1 = ( select someattr
from (nested select 1) as aux1
(nested select 2 (nested select 2.1 + nested select 2.2)) ) as aux2
where some_join_clauses
where t1.attr2 = 123
and t1.attr3 = 'abc'
Alias t1 shound be known at the level of nested select 1,2 and 2.1, 2.2? We are receiving an error message saying that t1.someattr is an invalid identifier. Can you help? Thanks!You can only reference elements nested 1 level deeper in a correlated update statement.
I'd suggest you try with the MERGE statement, or alternatively, post some sample data (insert statements) and table DDL (create statements), with an 'expected output' description and we can try to help you build a suitable statement. -
Emergency: problem with update statement!
hello guys, i have a very serious problem with an update statement in pl/sql.
i had an application written in sybase, where i had the following update statement:
update mis_dik_adeia
set trexon_etos_days = days_per_year
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_dik_adeia.adeia_id between :aapo and :aews
and mis_dik_adeia.employee_id = :erg
and mis_dik_adeia.etos = :etos
and mis_plafon_adeivn.years_yphr = ( select max( a.years_yphr ) from mis_plafon_adeivn a where a.adeia_id = mis_plafon_adeivn.adeia_id and a.years_yphr <= :eth ) using sqlca;
This is working properly in sybase. When i copied this code in pl/sql it displayed me error and it's impossible to work. Then i thought to make a nested select statement like this:
update mis_dik_adeia
set trexon_etos_days = (select days_per_year
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and mis_plafon_adeivn.years_yphr = (
select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth )
but as you can understand, it is working, but it doesn't produce the same results as the update statement in Sybase!
It is very important for me to solve this problem , which is a very big trouble for me for a long time.
Please if anyone can help me i would appreciate it a lot!
Regards ,
Bill...Bill,
folowing the logic of your original query by Sybase
(it's embedded SQL in Power Builder, isn't it ?):
update mis_dik_adeia
set trexon_etos_days = (select days_per_year
from mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_plafon_adeivn.years_yphr = (
select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth )
where
mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and
exists (select 1
from mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
and mis_plafon_adeivn.years_yphr = (
select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth )
In 9i you can also try the following:
megre into mis_dik_adeia
using (
select
days_per_year,
mis_dik_adeia.rowid rid
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and mis_plafon_adeivn.years_yphr =
(select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth)
) src
on (mis_dik_adeia.rowid = src.rid)
when matched then
update set mis_dik_adeia.trexon_etos_days = src.days_per_year
when not matched then
insert (mis_dik_adeia.adeia_id) values(0);
In 10G it can be easily:
megre into mis_dik_adeia
using (
select
days_per_year,
mis_dik_adeia.rowid rid
from mis_dik_adeia, mis_plafon_adeivn
where mis_dik_adeia.adeia_id = mis_plafon_adeivn.adeia_id
mis_dik_adeia.adeia_id between aapo and aews
and mis_dik_adeia.employee_id = erg
and mis_dik_adeia.etos = etos1
and mis_plafon_adeivn.years_yphr =
(select max( a.years_yphr )
from mis_plafon_adeivn a
where a.adeia_id = mis_plafon_adeivn.adeia_id
and a.years_yphr <= eth)
) src
on (mis_dik_adeia.rowid = src.rid)
when matched then
update set mis_dik_adeia.trexon_etos_days = src.days_per_year;
I have to notice I didn't check it carefully, so I can miss...
Rgds.
Corrected a mistake in the table name
Message was edited by:
dnikiforov -
Hello,
i want to write an sql-update statement where a field through a part of another field will be supplemented.
example:
update tabelle set targetDirectiory = ' export/home/VALUE_FROM_FIELD x' where blablabla
This should work as a subselect ?but I do not know how i can merge the strings
Thanks a lot.
LutzIt could have been better if you would have provided some supporting data. Anyway
You can do it like
UPDATE emp e
SET dept_name = 'DEPT-'||(SELECT d.dept_name
FROM dept d
WHERE d.dept_id = e.dept_id
WHERE blahblahblah;Regards
Arun -
Errors while running BPEL and incorrect UPDATE statement
Hi,
I installed following software.
1. Oracle Database 10g Release 2
2. SOA Suite 10g Release 3
3. Oracle JDeveloper (10.1.3.4)
I developed a BPEL process to lock a userid in PeopleSoft.
I have two issues.
a) I am getting error as shown below
b) its generating incorrect UPDATE statement, even though its assigning correct values in XML (UPDATE PSOPRDEFN SET LASTUPDOPRID = ?, OPRID = ? WHERE (ACCTLOCK = ?) i.e instead of setting OPRID in where clause its setting ACCTLOCK in where clause
<messages><input><Invoke_1_update_InputVariable><part xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="PsoprdefnCollection"><PsoprdefnCollection xmlns="http://xmlns.oracle.com/pcbpel/adapter/db/top/UpdateUserProfile">
<Psoprdefn>
<oprid>snagulapalli</oprid>
<version/>
<oprdefndesc/>
<emplid/>
<emailid/>
<oprclass/>
<rowsecclass/>
<operpswd/>
<encrypted/>
<symbolicid/>
<languageCd/>
<multilang/>
<currencyCd/>
<lastpswdchange/>
<acctlock>1</acctlock>
<prcsprflcls/>
<defaultnavhp/>
<failedlogins/>
<expent/>
<oprtype/>
<useridalias/>
<lastsignondttm/>
<lastupddttm/>
<lastupdoprid>Laptop BPEL</lastupdoprid>
<ptallowswitchuser/>
</Psoprdefn>
</PsoprdefnCollection>
</part></Invoke_1_update_InputVariable></input><fault><remoteFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="code"><code>17002</code>
</part><part name="summary"><summary>file:/D:/product/10.1.3.1/OracleAS_1/bpel/domains/default/tmp/.bpel_Sandbox_9.0_882edce22e996c64b48ea25cbe023033.tmp/Update_User_Profile.wsdl Update_User_Profile_ptt::update(PsoprdefnCollection) - WSIF JCA Execute of operation 'update' failed due to: DBWriteInteractionSpec Execute Failed Exception.
update failed. Descriptor name: http://UpdateUserProfile.Psoprdefn. Caused by: Io exception: Connection reset by peer: socket write error
; nested exception is:
ORABPEL-11616
DBWriteInteractionSpec Execute Failed Exception.
update failed. Descriptor name: http://UpdateUserProfile.Psoprdefn. Caused by: Io exception: Connection reset by peer: socket write error
Caused by Exception TOPLINK-4002 (Oracle TopLink - 10g Release 3 (10.1.3.1.0) (Build 061004)): oracle.toplink.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Io exception: Connection reset by peer: socket write errorError Code: 17002
Call:UPDATE PSOPRDEFN SET LASTUPDOPRID = ?, OPRID = ? WHERE (ACCTLOCK = ?)
bind => Laptop BPEL, snagulapalli, 1
Query:UpdateObjectQuery(<Psoprdefn 1 />).
</summary>
</part><part name="detail"><detail>
Internal Exception: java.sql.SQLException: Io exception: Connection reset by peer: socket write errorError Code: 17002
Call:UPDATE PSOPRDEFN SET LASTUPDOPRID = ?, OPRID = ? WHERE (ACCTLOCK = ?)
bind => Laptop BPEL, snagulapalli, 1
Query:UpdateObjectQuery(<Psoprdefn 1 />)</detail>
</part></remoteFault></fault></messages>
Regards,
Shanti Nagulapalli.What version of SOA Suite are you using, SOA Suite 10g Release 3 is not enough information. Make sure that it is the same as your JDev version if it isn't then either downgrade the JDev or upgrade the SOA Suite.
If you are still on SOA 10.1.3.1 then I would upgrade as there are many bugs in this release.
These kind of strange errors are generally caused by incompatibility between design time (JDev) and run time (SOA Suite)
cheers
James -
An update on a table was taking too long
The column being updated had an index . the time taken to update was around 120 mins (2 hrs) . I dropped the index and then ran the update statement. It took around 10 hrs. So i recreated the index on that column and ran the job. Now the time taken is around 4 hrs
Could you please let me know how to resolve this> Could you please let me know how to resolve this
By not taking pot shots in the dark.
The first step to any performance problem is Identification.
Identify the problem. Is it slow because of I/O? (e.g. is the process 80% of the time idle, waiting for I/O to complete?). It is because of CPU (e.g. single CPU machine running at 100% CPU busy time). Etc. Etc.
Only once an accurate diagnosis has been made, the problem can be treated.
In a nutshell:
Oracle has two basic measures for this (refer to the Oracle® Database Reference for details on virtual views for these):
- events (what is the session/process up to?)
- wait states (what is the session/process waiting for?)
The other aspect is determing what the process is attempting - just what execution plan results from the UPDATE session. E.g. if the wait states indicates a lot of I/O, the execution plan will point to the likely tables/indexes which is used that's causing this (.e.g full table scan, full index scans, index range scans, intensive/large nested loops, etc)
Also consult the Oracle® Database Performance Tuning Guide. -
Decode function in Update statement
Hello everyone,
I'm trying to write a query where I can update a pastdue_fees column in a book_trans table based on a difference between return_dte and due_dte columns.
I am using Oracle SQL. This is what I have so far for my decode function:
SQL> SELECT
2 DECODE(SIGN((return_dte - due_dte)*2),
3 '-1', '0',
4 '1', '12', 'Null')
5 FROM book_trans;
DECO
Null
12
Null
0
So the logic is that if the sign is -1, the value in return_dte column should be 0; if it's +1 then it's 12 and everything else is Null.
So now, I need to enter my decode function into the update statement to update the columns. However, I get error messages.
The logic should be:
UPDATE book_trans SET PastDue_fees = decode(expression)
I've given it a couple of different tries with the following results:
SQL> UPDATE book_trans
2 SET pastdue_fees = SELECT
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
SET pastdue_fees = SELECT
ERROR at line 2:
ORA-00936: missing expression
SQL> UPDATE book_trans
2 SET pastdue_fees =
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
FROM book_trans
ERROR at line 6:
ORA-00933: SQL command not properly ended
Any help or tips would be greatly appreciated as I've been taking SQL for about six weeks and not very proficient!
Thanks!882300 wrote:
Hello everyone,
I'm trying to write a query where I can update a pastdue_fees column in a book_trans table based on a difference between return_dte and due_dte columns.
I am using Oracle SQL. This is what I have so far for my decode function:
SQL> SELECT
2 DECODE(SIGN((return_dte - due_dte)*2),
3 '-1', '0',
4 '1', '12', 'Null')
5 FROM book_trans;
DECO
Null
12
Null
0
So the logic is that if the sign is -1, the value in return_dte column should be 0; if it's +1 then it's 12 and everything else is Null.
So now, I need to enter my decode function into the update statement to update the columns. However, I get error messages.
The logic should be:
UPDATE book_trans SET PastDue_fees = decode(expression)
I've given it a couple of different tries with the following results:
SQL> UPDATE book_trans
2 SET pastdue_fees = SELECT
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
SET pastdue_fees = SELECT
ERROR at line 2:
ORA-00936: missing expression
SQL> UPDATE book_trans
2 SET pastdue_fees =
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
FROM book_trans
ERROR at line 6:
ORA-00933: SQL command not properly ended
Any help or tips would be greatly appreciated as I've been taking SQL for about six weeks and not very proficient!
Thanks!If you really really really want to update the entire table, the syntax would be...
UPDATE book_trans
SET
pastdue_fees = DECODE(SIGN((return_dte - due_dte)*2), -1, 0, 1, 12, Null);I took out all the single quotes. If you actually have a string column and you're storing entirely numbers in it then it should be declared as a NUMBER column and not a character (varchar2) column.
ALWAYS use the proper data type, it'll save you a ton of headaches in the future.
Also, since you're new to the forum, please read the FAQ so you learn the etiquette and what not.
http://wikis.sun.com/display/Forums/Forums+FAQ -
Unable to execute an update statement using CallableStatement
Hi there,
I'm trying to run an update statement from JUnit using java.sql.CallableStatement and oracle.jbo.server.DBTransaction.
String updateSql =
"update footable set barcol=TO_DATE('12-SEP-09','dd-MM-yy') where bazcol = 505";
try {
statement =
applnModule.getDBTransaction().createCallableStatement(updateSql,
2);
int executeUpdate = statement.executeUpdate();
AppsLogger.write(this,
"# records UPDATED ------------------>" + executeUpdate,
AppsLogger.SEVERE);
} catch (SQLException s) {
s.printStackTrace();
Assert.fail("Encountered SQL Exception: " + s);
} finally {
try {
if (statement != null)
statement.close();
} catch (SQLException s) {
}Below is the exception I get when I run the above code. There is no problem with the SQL - it works fine from SQLDeveloper.
java.lang.AssertionError: Encountered SQL Exception: java.sql.SQLDataException: ORA-01858: a non-numeric character was found where a numeric was expected
org.junit.Assert.fail(Assert.java:91)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.invokeTestMethod(AtfJUnit4JTestCaseClassRunner.java:362)
oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.runMethods(AtfJUnit4JTestCaseClassRunner.java:272)
oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner$1.run(AtfJUnit4JTestCaseClassRunner.java:265)
org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.run(AtfJUnit4JTestCaseClassRunner.java:262)Edited by: 911023 on Oct 2, 2012 11:28 AM
Edited by: 911023 on Oct 2, 2012 11:30 AMUsing case statement.
UPDATE gor_gold_post
SET hoov_flag = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 304
OR
(TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
THEN 1
ELSE 99
END,
b49n = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 121.6
OR
(TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
THEN 1
ELSE 99
END
WHERE tariff_code IN (169, 135, 136);Note: Code not tested. -
Is their any limit on the number of column updates in a update statement!
Hello All,
Is their any limit on the number of columns to set in a single update statement.+
am using oracle 11g .
example :-
UPDATE FMLY SET as_comp1 = v_as_comp1 , as_comp2 = v_as_comp2, as_comp3 = v_as_comp3, as_comp4 = v_as_comp4 , as_comp5 = v_as_comp5 , perslt18 = v_perslt18 , persot64 = v_persot64 , fam_size = v_fam_size , numchild = total_children , C_AGE1 = v_c_age1, C_AGE2 = v_c_age2, C_AGE3 = v_c_age3, C_AGE4 = v_c_age4 WHERE FAMID = fmly_famid(i) ;
and also is it good practice to issue single update or multiple updates ?
example for the above update i can have multiple statements like .. does the performance matters if so which is good
UPDATE FMLY SET as_comp1 = v_as_comp1 , as_comp2 = v_as_comp2, as_comp3 = v_as_comp3, as_comp4 = v_as_comp4 , as_comp5 = v_as_comp5
WHERE FAMID = fmly_famid(i) ;
UPDATE FMLY SET perslt18 = v_perslt18 , persot64 = v_persot64 , fam_size = v_fam_size
WHERE FAMID = fmly_famid(i) ;
UPDATE FMLY SET numchild = total_children WHERE FAMID = fmly_famid(i) ;
UPDATE FMLY SET C_AGE1 = v_c_age1, C_AGE2 = v_c_age2, C_AGE3 = v_c_age3, C_AGE4 = v_c_age4 WHERE FAMID = fmly_famid(i) ;
thanks/kumar
Edited by: kumar73 on Sep 25, 2010 8:38 AMIf you can do it in a single SQL statement then you should do that.
Here's a mantra that I found to work out pretty good:
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:73891904732164 -
Error while schedulingg update stat in db13
Dear Experts,
Please look into my issue we are facing an error while scheduling update statistics in db13 and I tried to open detailed log
It is given
SXPG_COMMAND_EXECUTE failed for BRTOOLS - Reason: program_start_error: For More Information, See SYS
Please help me how to solve this my error
RegardsHi,
Check the owner for BRBACKUP, BRARCHIVE, and BRCONNECT in kernel,
these files should be with SIDADM, if not change the owner to SIDADM and rerun the update stats.
and also Refer the note 446172
Regards,
Ram -
How do I pass multiple values from a text box to an update statement
I hope this does not sound to lame. I am trying to update multiple values Like this:
Code|| Computer Desc || Computer Price || Computer Name
SEL1 || Apple macbook || 1564 || Apple Macbook Basic
SEL2 || Dell 630 || 1470 || Dell Latitude
I want to change all six values at once in one update statement based on the Code, I can't find a good tutorial/example to help me.
Can anyone point me in the right direction?
Thanks so much,
LauraYou can do conditional updates with decode or case statements e.g.
SQL> create table t as
2 select 'SEL1' as code, 'Apple macbook' as comp_desc, 1564 as comp_price, 'Apple Maxbook Basic' as comp_name from dual union
3 select 'SEL2', 'Dell 630', 1470, 'Dell Latitude' from dual
4 /
Table created.
SQL>
SQL> update t
2 set comp_desc = CASE code WHEN 'SEL1' THEN 'Test1' Else 'Test2' END,
3 comp_price = CASE code WHEN 'SEL1' THEN 1234 Else 2345 END,
4 comp_name = CASE code WHEN 'SEL1' THEN 'Test1 Name' Else 'Test2 Name' END
5 /
2 rows updated.
SQL>
SQL> select * from t
2 /
CODE COMP_DESC COMP_PRICE COMP_NAME
SEL1 Test1 1234 Test1 Name
SEL2 Test2 2345 Test2 Name
SQL> -
Need help to write a query for Update statement with join
Hi there,
The following update statement gives me error as the given table in set statement is invalid. But its the right table .
Is the statement correct? Please help .
update (
select distinct(vpproadside.VEHICLE_CRED_OVERRIDE.vin)
from vpproadside.VEHICLE_CRED_OVERRIDE
join vpproadside.vpp_vehicle
on vpproadside.vpp_vehicle.vin = vpproadside.VEHICLE_CRED_OVERRIDE.vin
where VPP_CARRIER_SEQ_NUMBER = 90
and EXPIRY_DATE = '17-MAR-10'
set vpproadside.VEHICLE_CRED_OVERRIDE.EXPIRY_DATE = '15-SEP-10';Edited by: Indhu Ram on Mar 12, 2010 1:00 PM
Edited by: Indhu Ram on Mar 12, 2010 1:22 PM
Edited by: Indhu Ram on Mar 12, 2010 2:35 PM
Edited by: Indhu Ram on Mar 15, 2010 8:04 AM
Edited by: Indhu Ram on Mar 15, 2010 8:06 AM
Edited by: Indhu Ram on Mar 15, 2010 8:28 AMAsk Tom has very good discussion about this, if UPDATE does not work for PK issue, you can use MERGE
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:760068400346785797 -
Running an update statement on two dependent attributes
Dear All,
I have a repair_job table that contains values for work_cost, parts_cost and total_cost which is the sum of the work and parts cost values. I want to run an update statement that doubles the work cost and, naturally, updates the value of total cost as well. I tried to run it as:
update repair_job
set work_cost = 2 * work_cost, total_cost = work_cost + parts_cost
where licence in (
select licence from car
where year = to_char(sysdate,'YYYY')
thinking that because the update of work_cost is first on the list, the updated value of total cost would be correct. It seems however that the update of total cost happens first and then the work cost is been updated; not sure what the reason is for that and it happens no matter what the order is in the update statement.
I know that I can do it in two separate statements, or use a trigger or PL/SQL to do it but I am curious as to why it has this behaviour. Also, is there a way to do it in a single SQL statement - i.e. forcing the update of the work_cost attribute first and then that of total_cost?
I look forward to hearing from you soon.
Regards,
GeorgeWelcome to the forum!
>
thinking that because the update of work_cost is first on the list, the updated value of total cost would be correct. It seems however that the update of total cost happens first and then the work cost is been updated; not sure what the reason is for that and it happens no matter what the order is in the update statement.
I know that I can do it in two separate statements, or use a trigger or PL/SQL to do it but I am curious as to why it has this behaviour. Also, is there a way to do it in a single SQL statement - i.e. forcing the update of the work_cost attribute first and then that of total_cost?
>
The update to all columns of the row happen at the same time - there is no order involved.
You don't need two statements but you do need to do the updates based on the current value of the columns.
set work_cost = 2 * work_cost, total_cost = 2 * work_cost + parts_cost----------
In addition to sb92075's comments in 11 g you could also just define a virtual column for total_cost and then just query it like you do now.
total_cost NUMBER GENERATED ALWAYS AS (work_cost + parts_cost) VIRTUAL,See this Oracle-base article for an example
http://www.oracle-base.com/articles/11g/virtual-columns-11gr1.php
Edited to supplement sb92075's reply by mentioning virtual columns -
How can i use multiple row subquery in update statement
Hai All
I using group function in my update statement.. and i need to update more rows so i need to use multiple row
subquery pls tell me how to use multiple row subquery in update statement
For example
while i am using this like this i got an error
update dail_att set outtime in (select max(r2.ptime) from temp_att where empcode=r2.enpno and
barcode=r2.cardn and attend_date=r2.pdate group by enpno,pdate,cardn);
Pls tell me how to use with example
Thanks & regards
Srikkanth.MHai Man
Thanks for ur response Let me clear what i need
First step Fetch the records as text file and stores into table T1
and the next step is i have seperated the text using substring and stores in different columns of a table
There are two shifts 0815 to 1645 and 1200 and 2000
Here I rep IN and O rep OUT
Empno date time inout
001 01-01-10 0815 I
002 01-01-10 0815 I
003 01-01-10 0818 I
001 01-01-10 1100 0
001 01-01-10 1130 I
002 01-01-10 1145 0
002 01-01-10 1215 I
004 01-01-10 1200 I
005 01-01-10 1215 I
004 01-01-10 1315 O
004 01-01-10 1345 I
001 01-01-10 1645 0
002 01-01-10 1715 0
003 01-01-10 1718 0
004 01-01-10 2010 0
005 01-01-10 2015 0
This is my T1 table i have taken data from text file and stored in this table from this table i need to move data to another table T2
T2 contains like this
Empno Intime Intrin Introut Outtime Date
001 0815 1100 1130 1645 01-01-10
002 0815 1145 1215 1715 01-01-10
003 0818 1718 01-01-10
004 1200 1315 1345 2010 01-01-10
005 1215 2015 01-01-10
This what i am trying to do man but i have little bit problems Pls give some solution with good example
And my coding is
declare
emp_code varchar2(25);
in_time varchar2(25);
out_time varchar2(25);
Cursor P1 is
Select REASON,ECODE,READMODE,EMPD,ENPNO,FILL,PDATE,PTIME,INOUT,CARDN,READERN
From temp_att
group by REASON,ECODE,READMODE,EMPD,ENPNO,FILL,PDATE,PTIME,INOUT,CARDN,READERN
ORDER BY enpno,pdate,ptime;
begin
for r2 in p1 loop
declare
bar_code varchar2(25);
begin
select barcode into bar_code from dail_att where empcode=r2.enpno and attend_date=r2.pdate;
For r3 in (select empcode,empname,barcode,intime,intrin,introut,addin,addout,outtime,attend_date from dail_att)loop
if r2.inout ='O' then
update dail_att set outtime =(select max(r2.ptime) from temp_att where empcode=r2.enpno and barcode=r2.cardn and attend_date=r2.pdate group by r2.cardn,r2.enpno,r2.pdate );
end if;
end loop;
exception
when no_data_found then
if r2.inout ='I' then
insert into dail_att(barcode,empcode,intime,attend_date)(select r2.cardn,r2.enpno,min(r2.ptime),r2.pdate from temp_att group by r2.cardn,r2.enpno,r2.pdate );
end if;
end;
end loop;
commit;
end;
Pls tell me what correction i need to do i the update statement i have used a subquery with group function but when i used it will return only one row but my need is to return many rows and i need to use multiple row subquery
and how can i use it in the update statement
Thanks In Advance
Srikkanth.M -
How to use the updated value in the same update statement
Hello,
I just wonder how to use the updated new value of other column in the same udpate statement. I am using Oracle 11.2, and want to update the two columns with one update statement as following:
create table tb_test (id number(5), tot number(5), mon_tot number(5));
update tb_test set (tot = 15, mon_tot = tot *15) where id = 1;
...I would like to update both tot and mon_tot column, the value of mon_tot shall be determinted by the new value of tot.
Thanks,
Edited by: 939569 on 1-Feb-2013 7:00 AMEdit: example added
SQL> create table tb_test
2 ( id number(5)
3 , tot number(5)
4 , mon_tot number generated always as (tot*15) virtual
5 );
Table created.
SQL> insert into tb_test (id, tot) values (1, 5);
1 row created.
SQL> select * from tb_test;
ID TOT MON_TOT
1 5 75
1 row selected.
SQL> update tb_test
2 set tot = 15
3 where id = 1;
1 row updated.
SQL> select * from tb_test;
ID TOT MON_TOT
1 15 225
1 row selected.
Maybe you are looking for
-
What's the Best iPhone case????
I like to keep my phone in my pocket but in doing so gets a lot of dust and lint on it. Is there any case out there that would work better against dust build up. I not that worried right now, but over the years the build up could get inside and slow
-
6230i help ! :( convert problems
hello pleas please please can anyone help me ? I have just bought a 6230i mobile phone and its driving me round the bend ! I am desperatly trying to download tracks from windows media player 11 to my phone,it downloads ok but when I go to play the so
-
Clone Stamp & Paintbrush cursor not displaying on image
Hey there, When attempting to edit a photo (on PS CS3), the cursor for the paintbrush and clone stamp tools does not display on the image - it'll come up when the mouse isn't directly over it (ie around the borders, & workspace etc, but not on the im
-
hi, I am doing BDC program for F-37 transaction i have no of line items. how can i loop only at item level.kindly help me on this. Thanks & Regards, Mani Malathi.
-
Earlier this year we migrated/upgraded our GW7 (NetWare 6.5) system to GW8 (SLES) and there were a few issues that we didn't pick up until a week or 2 later. Most of these have been fixed up now, but we have a few issues with our document libraries.