Update statement using function
Environment: Win7 and SQL server 2008 R2
Tools: SQL management tool 2008 R2
Problem: I have been trying to update id numbers in the staging table. T-SQL statement updates all id number in the staging table, but what if the we have multiple records for the same person who we are assigning the ID to his/her record. It should generate
one pn_id per ssn regadless if there are several records for the same individual. for example, my code assigns the following id:
Student table (ID, ssn, name, subject, grade, year)
(288258466,192160792 , Sally Johnson, Math, A, 2014 )
(176268917, 192160792, Sally Johnson, Spanish, B+, 2014 )
(900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
(704099635, 770616858, Jessica Simpson, IT, A, 2014 )
(704099640, 444718562, Douglas Mike, IT, A, 2014 )
(288258450, 31883459, Susan Jesson, IT, A, 2014 )
(176268960, 260518681, Veronica Floris, IT, A, 2014 )
The expected results should be as the following in the staging table
Student table (ID, ssn, name, subject, grade, year)
(288258466,192160792 , Sally Johnson, Math, A, 2014 )
(288258466, 192160792, Sally Johnson, Spanish, B+, 2014 )
(900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
(900303787, 770616858, Jessica Simpson, IT, A, 2014 )
(704099640, 444718562, Douglas Mike, IT, A, 2014 )
(288258450, 31883459, Susan Jesson, IT, A, 2014 )
(176268960, 260518681, Veronica Floris, IT, A, 2014 )
My code:
UPDATE a
SET pn_id = (Select dbo.gen_id())
from [dbo].[Staging_Table] a
where SSN in (Select SSN from [dbo].[staging_Table]
group by SSN having count(SSN) > 1)
GO
I also tried the following code but no success
;with cte
As
Select * , ROW_NUMBER() Over(Partition BY ssn Order by ssn) As MyCount
from dbo.Staging_Table
Select * into #a from cte where MyCount=1
UPDATE a
SET pn_id = (Select dbo.fn_gen_id())
from staging_table a
Full join #a b on a.ssn = b.ssn
Drop table #a
please help.
I ran some tests and Sandra is correct, you don't always get the same value for all occurrences of the same SSN.
After thinking about this, I think I understand why this happens.
With functions, SQL is allowed to assume that multiple calls to a function in a single command with the same parameter values always return the same result. That's why functions cannot use side-effecting functions and is not allowed to make changes
to any table except table variables declared in the function.
And SQL is allowed to rearrange the processing of a command in any manner it believes is most efficient as long as it returns the same result. So even though the query I gave says first get a set of distinct SSN's and then calls the function only once
for each SSN, it is valid for SQL to instead call the function once for each row in the original table since this function has no parameters and is therefore should return the same value on each call. But since the function being called apparently (we've
not seen the code of the function) returns different values on different calls, the same SSN could be assigned different values, but SQL would still be working correctly.
Note that it would also be valid for SQL to notice that this function has no parameters and therefore should return the same value every time it is called within the same command and so just call the function once per execution of the command. This
would mean that every SSN would get the same ID. As far as I can determine currently SQL does not do that but a different version in the future with a different optimizer might.
Tom
Similar Messages
-
Explain plan on Update statement in function
All,
I have an update statement in a function and my explain plan shows:
"Optimizer" "Cost" "Cardinality" "Bytes"
"UPDATE STATEMENT" "ALL_ROWS" "2" "1" "7"
"UPDATE user.<table_name>" "" "" "" ""
"INDEX(UNIQUE SCAN) <table_name>.<PK_column_cons>" "ANALYZED" "1" "1" "7"
Filtering is on index unique column, but cost is 1 what does that mean?
do i need to change my update statement in function?
Any ideas?
Regards,
~ORAThe cost is the optimizer's measure of how much effort it will take to execute the statement. For any statement the optimizer will evaluate a number of execution plans and choose the one with the lowest cost. I wouldn't worry too much about what it actually "means". However if you want to understand this subject in a lot more detail I would recommend the book Cost-Based Oracle Fundamentals by Jonathan Lewis.
For your update statement the optimizer has chosen to access a single row by the primary key index, which is probably good enough, so you should not need to change it.
The only faster way to access the data would be to use the row's ROWID directly. You would need to have fetched this explicitly in a previous SELECT statement, or you could use it implicitly with the WHERE CURRENT OF syntax for a cursor opened with FOR UPDATE. -
Write an UPdate statement using the logic used in PL/SQL block (oracle 10g)
Hi All,
I have written the following PL/SQL block. I want to write an UPDATE statement using the logic used in the following PL/SQL block. can any one please help me out in this regards.
DECLARE
v_hoov_fag gor_gold_post.hoov_flg%TYPE;
v_b49n gor_gold_post.b49n%TYPE;
CURSOR c
IS
SELECT bs_id, loyalty_date, loyalty_period, contract_date
FROM gor_gold_post
WHERE tariff_code IN (169, 135, 136);
BEGIN
FOR rec IN c
LOOP
IF (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
v_hoov_flg := 1;
ELSE
v_hoover_flag := 99;
END IF;
IF (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
v_b49n := 1;
ELSE
v_b49n := 99;
END IF;
UPDATE gor_gold_post
SET hoov_flg = v_hoov_flg,
b49n = v_b49n
WHERE bs_id = rec.bs_id AND tariff_code IN (169, 135, 136);
COMMIT;
END LOOP;
END;Thank you,Using 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. -
'Missing select' error for update statement using WITH clause
Hi,
I am getting the below error for update statement using WITH clause
SQL Error: ORA-00928: missing SELECT keyword
UPDATE A
set A.col1 = 'val1'
where
A.col2 IN (
WITH D AS
SELECT col2 FROM
(SELECT col2, MIN(datecol) col3 FROM DS
WHERE <conditions>
GROUP BY PATIENT) D2
WHERE
<conditions on A.col4 and D2.col3>Hi,
The format of a query using WITH is:
WITH d AS
SELECT ... -- sub_query
SELECT ... -- main query
You don't have a main query. The keyword FROM has to come immediately after the right ')' that ends the last WITH clause sub-query.
That explains the problem based on what you posted. I can't tell if the real problem is in the conditions that you didn't post.
I hope this answers your question.
If not, post a complete test script that people can run to re-create the problem and test their ideas. Include a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
Is it possible that my update stats used only correct tables?
Whenever there is a schedule maintenance run I receive a error:
Executing the query "UPDATE STATISTICS [Perf].[PerfHourly_F65954CD35A54..." failed with the following error: "Table 'PerfHourly_F65954CD35A549E886A48E53F148F277' does not exist.". Possible failure reasons: Problems with the query, "ResultSet"
property not set correctly, parameters not set correctly, or connection not established correctly.
Is it possible that my update stats used only correct tables?
ThanksUse below script ...(change if required)
USE [dbname]
go
DECLARE @mytable_id INT
DECLARE @mytable VARCHAR(100)
DECLARE @owner VARCHAR(128)
DECLARE @SQL VARCHAR(256)
SELECT @mytable_id = MIN(object_id)
FROM sys.tables WITH(NOLOCK)
WHERE is_ms_shipped = 0
WHILE @mytable_id IS NOT NULL
BEGIN
SELECT @owner = SCHEMA_NAME(schema_id), @mytable = name
FROM sys.tables
WHERE object_id = @mytable_id
SELECT @SQL = 'UPDATE STATISTICS '+ QUOTENAME(@owner) +'.' + QUOTENAME(@mytable) +' WITH ALL, FULLSCAN;'
Print @SQL
EXEC (@SQL)
SELECT @mytable_id = MIN(object_id)
FROM sys.tables WITH(NOLOCK)
WHERE object_id > @mytable_id
AND is_ms_shipped = 0
END
Or use below for required table only but it will not execute only generate script, make change as per ur requirements:
SELECT X.*,
ISNULL(CASE
WHEN X.[Total Rows]<=1000
THEN
CASE
WHEN [Percent Modified] >=20.0
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN --20% Small Table Rule'
END
WHEN [Percent Modified] = 100.00
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN --100% No real Stats Rule'
--WHEN X.[Rows Modified] > 1000
--THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN --1000 Rows Modified Rule'
ELSE
CASE
WHEN X.[Total Rows] > 1000000000 --billion rows
THEN CASE
WHEN [Percent Modified] > 0.1
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN -- 1B Big Table Rule'
END
WHEN X.[Total Rows] > 100000000 --hundred million rows
THEN CASE
WHEN [Percent Modified] > 1.0
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN -- 100M Big Table Rule'
END
WHEN X.[Total Rows] > 10000000 --ten million rows
THEN CASE
WHEN [Percent Modified] > 2.0
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN -- 10M Big Table Rule'
END
WHEN X.[Total Rows] > 1000000 --million rows
THEN CASE
WHEN [Percent Modified] > 5.0
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN -- 1M Big Table Rule'
END
WHEN X.[Total Rows] > 100000 --hundred thousand rows
THEN CASE
WHEN [Percent Modified] > 10.0
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN -- 100K Big Table Rule'
END
WHEN X.[Total Rows] > 10000 --ten thousand rows
THEN CASE
WHEN [Percent Modified] > 20.0
THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN -- 10K Big Table Rule'
END
END
END,'') AS [Statistics SQL]
FROM (
SELECT DISTINCT
DB_NAME() AS [Database],
S.name AS [Schema Name],
T.name AS [Table Name],
I.rowmodctr AS [Rows Modified],
P.rows AS [Total Rows],
CASE
WHEN I.rowmodctr > P.rows
THEN 100
ELSE CONVERT(decimal(8,2),((I.rowmodctr * 1.0) / P.rows * 1.) * 100.0)
END AS [Percent Modified]
FROM
sys.partitions P
INNER JOIN sys.tables T ON P.object_Id = T.object_id
INNER JOIN sys.schemas S ON T.schema_id = S.schema_id
INNER JOIN sysindexes I ON P.object_id = I.id
WHERE P.index_id in (0,1)
AND I.rowmodctr > 0
) X
WHERE [Rows Modified] > 1000
ORDER BY [Rows Modified] DESC
Please click "Propose As Answer"
if a post solves your problem, or "Vote As Helpful" if a post has been useful
to you -
Update Statement through function
Hi,
I've got the following select statement that is pulling 29 records:
select distinct aqh.quote_number, aqh.quote_header_id,aqh.quote_version, aql.line_number, msi.inventory_item_id, msi.segment1
,aqh.price_list_id, aqh.quote_expiration_date,aql.line_list_price, qpv.operand
from aso_quote_headers_all aqh, aso_quote_lines_all aql,mtl_system_items msi
,qp_list_headers qlh, qp_list_lines qpl, qp_list_lines_v qpv
where aqh.quote_header_id = aql.quote_header_id
and aql.inventory_item_id = msi.inventory_item_id
and aqh.price_list_id = qlh.list_header_id
and qlh.list_header_id = qpl.list_header_id
and qlh.list_header_id = qpv.list_header_id
and qpl.list_line_id = qpv.list_line_id
and msi.inventory_item_id = qpv.product_id
and aqh.quote_number = :quote_number --56530
i need to update the operand = list_line_price, for all the multiple 29 records. for every quote_number and quote_version_no.
i need help in this to write a function with update statement.
Thanks and RegardsHi,
whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements) for all the tables, and the results you want from that data. In the case of a DML operation (like UPDATE) the results will be the contents of the changed table after the DML is finished.
MERGE may be easier to use than UPDATE in this case.
Put your existing query in the USING clause. The only columns it needs to include in the SELECT clause are those that identify which rows to update, and the new values (line_list_price in this case). I assume that the table to be updated has a unique key, which I called primary_key in the example below. This can actually be two or more columns, but it can't include the column being updated (operand).
I assume that all the tables and all the conditions in your original query are necessary to get the columns in the SELECT clause. If not, you can simplify the query.
MERGE INTO qp_list_lines_v dst
USING (
select distinct aql.line_list_price, qpv.primary_key
from aso_quote_headers_all aqh, aso_quote_lines_all aql,mtl_system_items msi
,qp_list_headers qlh, qp_list_lines qpl, qp_list_lines_v qpv
where aqh.quote_header_id = aql.quote_header_id
and aql.inventory_item_id = msi.inventory_item_id
and aqh.price_list_id = qlh.list_header_id
and qlh.list_header_id = qpl.list_header_id
and qlh.list_header_id = qpv.list_header_id
and qpl.list_line_id = qpv.list_line_id
and msi.inventory_item_id = qpv.product_id
and aqh.quote_number = :quote_number --56530
) src
ON (src.primary_key = dst.primary_key)
WHEN MATCHED THEN UPDATE
SET dst.operand = src.list_line_price;You can use a MERGE statement like this in a PL/SQL procedure or function. (If you put this in a function, then you can only call the function from PL/SQL; you can't use a function that performs DML in a SQL query.)
As posted above, the statement will use a single, given quote_number. (You mentioned another column, quote_version_number, that does not appear in your original query. It's unclear what you want with that column.)
You can replace the bind variable :quote_number with an argument to the procedure, as Achyut suggested. It will still only work on a single, given quote_number.
If you want it to work on all quote numbers at once, then omit the last condition (the one that references quote_number), or change it to
AND aqh.quote_number IS NOT NULLdepending on your needs.
If you want more help, post some sample data and the desired results. -
Material group updation by using function modules
Hello All,
I would like to add , update and delete material group From database tables T023 and T023T according to the given Excel input file.Could you please suggest me any function modules are there apart form MATL_GROUP_UPDATE .
if i am using this function module i am getting the follwing error
'Class does not exist or is not valid on this date'.
Could you please send me any sample code.
Thanks in advance,
Arvind.Hello Narendran,
Thanks for your quick reply.
i need to do the following fucntions to the tables t023 and t023t.
1) adding material group
2) Updating the material group
3) Deleting the material group
according to the status field in the excel input file as shown below
Status ungültig Referenzen MGS Beschreibung deutsch Beschreibung englisch 中文 Beschreibung russisch
N H4*** Kohlen Carbon 炭 Уголь
N H4100 Kohlebürsten Carbon brushes 炭刷 Угольные щетки
N H4900 Sonstige Teile aus Kohle, techn. Kohle Other parts made from carbon, techn. carbon 由炭,工程用炭制成的其他零件 Прочие виды изделий из угля, технический уголь
U J2100 Polyphenylenether (PPESIB) Polyphenylene oxide (PPO) 聚苯氧化物(聚苯撑氧,聚苯撑氧化物)(PPO) Полифенилэфир (PPESIB)
D x J2400 Sonstige styrolhaltige Polymere Other Polymers Containing Styrene 其他含苯乙烯聚合物 Прочие виды полимеров, содержащие стирол
Note:Status :N means add the corresponding material group H4***
U means update the material group Description in t023t
D means delete the material group form the table t023t
in all languages
Could you please tell me any other fucntion modules are there.
As per your suggession we can add the material groups then what about Updation and deletion of material groups.
Also suggest me shall i go for normal modify , delete and update statements in my program to aceive the above functionality
2) The excel file format is also not constant they can change the columns
as per their wish i mean for exp in the above excel at col1 Status field is there and at col4 (MGS ) material group and remaining columns are description of the material group in different languages(sorry the excel alignment is not clear above) .
They can change this and they can place status at col5 and MGS at col6 .
Could you please advice me how to handle this situation in my program
Thanks in advance,
Arvind. -
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. -
Problem in Update statement using Execute Immediate
Hi All,
I am facing problem in update statement.
I am creating dynamic sql and use "execute immediate" statement to execute a update statement.
But it is not updating any thing there in the table.
I have created a query like :
update_query='Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
Execute immediate update_query using V_Id;
commit;
But it is not updating the table.
I have a question , is execute immediate only does insert and delete?
Thanks
AshokSQL> select * from t;
TID P
101 N
SQL> declare
2 V_Id number := 101;
3 Table_Name varchar2(30) := 'T';
4 update_query varchar2(1000);
5 begin
6 update_query := 'Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
7 Execute immediate update_query using V_Id;
8 commit;
9 end;
10 /
PL/SQL procedure successfully completed.
SQL> select * from t;
TID P
101 Y -
Update Statement using SELECT statement
The following select query return 1 record to me
[code]
select deptno , dname, empno , max_date, max(v_num)
from (select d.deptno , d.dname , e.empno ,max (ver_date) over(partition by d.id ,d.no) max_date ,v_num
from emp e ,dept d
where e.deptno=d.deptno and e.dname = d.dname and e.empno=1 and d.deptno =3 )
group by deptno , dname, empno , max_date
[/code]
Now I need to update the above value to the emp table itself
In emp table for the empno=1 I need to update the columns mx_Date and v_num columns with the above last 2 columns in the select statement (max_date, max(v_num) )
How can I write the update statement for this.
Thank YouSomething like this
merge into emp e1
using (
select deptno
, dname
, empno
, max_date
, max(v_num) v_num
from (
select d.deptno
, d.dname
, e.empno
, max (ver_date) over(partition by d.id , d.no) max_date
, v_num
from emp e
, dept d
where e.deptno = d.deptno
and e.dname = d.dname
and e.empno = 1
and d.deptno = 3
group
by deptno
, dname
, empno
, max_date
) e2
on (
e1.empno = e2.empno
when matched then
update set e1.mx_date = e2.max_date,
e1.v_num = e2.v_num -
Hello my friends
I have one table "encompasses": continent,country,percentage
now the update should change the continent field, all "Europe" to "Asia" and all "Asia" to "America" and "America" to "Europe" by using case and just one update statement.
I wrote so and i got this error
Error starting at line 2 in command:
UPDATE encompasses
SET continent=
CASE WHEN continent='Europe' THEN 'Asia'
WHEN continent='Asia' THEN 'America'
WHEN continent='America' THEN 'Europe'
END
Error report:
SQL Error: ORA-01407: cannot update ("intern"."ENCOMPASSES"."CONTINENT") to NULL
01407. 00000 - "cannot update (%s) to NULL"
*Cause:
*Action:please give me hints,thank u.
-- File created - Monday-May-13-2013
CREATE TABLE "intern"."ENCOMPASSES" ("COUNTRY" CHAR(2), "CONTINENT" VARCHAR2(20), "PERCENTAGE" NUMBER)
COMMENT ON COLUMN "intern"."ENCOMPASSES"."COUNTRY" IS 'the country code'
COMMENT ON COLUMN "intern"."ENCOMPASSES"."CONTINENT" IS 'the continent name'
COMMENT ON COLUMN "intern"."ENCOMPASSES"."PERCENTAGE" IS 'percentage, how much of the area of a country belongs to the
continent'
COMMENT ON TABLE "intern"."ENCOMPASSES" IS 'information to which continents a country belongs'
REM INSERTING into intern.ENCOMPASSES
SET DEFINE OFF;
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('cx','Asia',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('eg','Asia',10);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('ge','Asia',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('id','Asia',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('ad','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('al','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('at','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('ba','Europe',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pa','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pe','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pm','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('pr','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('py','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('sr','America',100);
Insert into intern.ENCOMPASSES (COUNTRY,CONTINENT,PERCENTAGE) values ('sv','America',100);thank you, im using oracle 11g and ubuntu12
best,david
Edited by: 1003209 on 13-May-2013 10:121003209 wrote:
Hello my friends
I have one table "encompasses": continent,country,percentage
now the update should change the continent field, all "Europe" to "Asia" and all "Asia" to "America" and "America" to "Europe" by using case and just one update statement.
I wrote so and i got this error
Error starting at line 2 in command:
UPDATE encompasses
SET continent=
CASE WHEN continent='Europe' THEN 'Asia'
WHEN continent='Asia' THEN 'America'
WHEN continent='America' THEN 'Europe'
END
Error report:
SQL Error: ORA-01407: cannot update ("intern"."ENCOMPASSES"."CONTINENT") to NULL
01407. 00000 - "cannot update (%s) to NULL"
*Cause:
*Action:This seems the column Continent has not null contraint on it, hence when there is a continent other than the three you mentioned above the case statement is evaluating it to null and hence failing e.g. if there is a record with continent = 'Antartica' it will try to update that as null.
so either add this:
WHERE continent in ('Europe' ,'Asia','America')this will update only for this continents and ignore other values.
If you want to update other continents as well then have a else condition in CASE statement to assign defualt value.
Regards,
Santosh -
Problem with a sqlite update statement using variables
Flash Builder/Flex 4
I'm trying to create a routine that will allow me to change the name of an author in a sqlite table.
I have this update statement which works with hardcoded data:
//trace("updateName function newAuthorName: " + newAuthorName (returns Dusty));
//trace("updateName function oldAuthorName: " + oldAuthorName (returns Kristin));
updateStmt = new SQLStatement();
updateStmt.sqlConnection = conn;
var sql:String = "UPDATE tableName SET authorNameColumn = 'Dusty' WHERE authorNameColumn = 'Kristin' ";
updateStmt.text = sql;
updateStmt.execute();
If I change the statement to
"UPDATE tableName SET authorNameColumn =" + newAuthorName + "WHERE authorNameColumn =" + oldAuthorName;
I get SELECT error: SQLError: 'Error #3115: SQL Error.', details:'near 'authorNameColumn': syntax error'
I've tried changing many things about this statement trying to isolate the problem, but it seems to not like the variables.Lee;
Thanks for your help.
I'm relatively new to this Flex stuff.
I've been trying to fix this problem for hours and you know how it is when you keep looking at the same thing for too long.
The article you linked to helped. I finally just copied the text from it and changed the variable name to my own.
FINALLY!! I can go do something else now.
Grins
Kristin -
Update statement using correlated partition over query - help asked please.
A simple table:
SQL> desc vs
Name Null? Type
COL1 VARCHAR2(10)
COL2 NUMBER
SQL> select * from vs;
COL1 COL2
A
A
B
B
B
C
D
D
E
E
E
E
E
13 rows selected.
I want to Update col2 with sequence number grouped by col1, in one step.
EG. The seqno returned by:
select col1, row_number() over (partition by col1 order by rowid) seqno
from vs;
COL1 SEQNO
A 1
A 2
B 1
B 2
B 3
C 1
D 1
D 2
E 1
E 2
E 3
E 4
E 5
13 rows selected.
And UPDATE col2 with the seqno.
The following worked:
merge into vs v1
using (select row_number() over (partition by col1 order by rowid)seqno,rowid from vs) v
on (v1.rowid=v.rowid)
when matched then update set v1.col2 = v.seqno
when not matched then insert (v1.col1,v1.col2)
values('Z',null);
13 rows merged.
SQL> select * from vs;
COL1 COL2
A 1
A 2
B 1
B 2
B 3
C 1
D 1
D 2
E 1
E 2
E 3
E 4
E 5
13 rows selected.
Can someone help with a simpler UPDATE or WITH ... statement?
==============
This isn't urgent, just frustrated with syntax ;-)
Best wishes of the season.Thank you for the reply.
I've figured it out (with help).
update vs a
set col2 =
(select seq from
select rowid, row_number() over (partition by col1 order by rowid) as seq
from vs
) b
where a.rowid = b.rowid
To complicate things (for my own interest)
If some of the col2 were not null, and I had to sequence the null rows starting above the maximum value already used, I got this to work.
SQL> select * from vs;
COL1 COL2
A 1
A 2
B 1
B 2
B 3
C
D 1
D 2
E 1
E 10
E
E
E
update vs a
set col2 =
(select seq from
select rowid, row_number() over (partition by col1 order by rowid)+
(select max(nvl(col2,0)) from vs vsa where vsa.col1=vs.col1) as seq
from vs
where col2 is null
order by col2 nulls last
) b
where a.rowid = b.rowid
where col2 is null;
SQL> select * from vs;
COL1 COL2
A 1
A 2
B 1
B 2
B 3
C 1
D 1
D 2
E 1
E 10
E 11
E 12
E 13
Might be helpful to someone else one day. Cheers everybody. -
Insert statements using function are slow in 10.2.0.3
I am migrating our data warehouse server to newer more powerful hardware, both server and disk are far superior. As part of the migration the oracle rdbms version is also changing from 10.1.0.3 to 10.2.0.3 on RHEL4.
We have some jobs that run and populate some fact tables and when the insert runs on the new server it is at least 6 times slower that on the older hardware. The job that does the inserts uses some funtions to populate some fileds and seems to be the culprit quite possibly?
I can insert many rows quickly in the same table space with all of the same storage parameters and this goes really fast but when we call the functions it really slows down to a crawl?
Is is possible this could be a bug in the 10.2.0.3 rdbms version?You have not provided substantial amounts of information required to help you.
Here is a partial list.
1. Has anyone collected system statistics on the new system?
http://www.morganslibrary.org/reference/system_stats.html
2. Has anyone produced Explain Plan reports with DBMS_XPLAN to see if the plans are different?
http://www.morganslibrary.org/reference/explain_plan.html
3. Has anyone run StatsPacks to compare the systems?
http://tahiti.oracle.com
We can't help you without knowing what is different. -
What lock does the Update Statement use?
Hi All,
Does the below statement will put a row level lock or exclusive lock.
update employee set emp_name='Emp1' where emp_id=1;
Regards
WUKJA@ukja102> drop table t1 purge;
Table dropped.
Elapsed: 00:00:00.93
UKJA@ukja102> create table t1(c1 int);
Table created.
Elapsed: 00:00:00.09
UKJA@ukja102>
UKJA@ukja102> insert into t1 values(1);
1 row created.
Elapsed: 00:00:00.00
UKJA@ukja102> commit;
Commit complete.
Elapsed: 00:00:00.03
UKJA@ukja102>
UKJA@ukja102> update t1 set c1 = 2;
1 row updated.
Elapsed: 00:00:00.00
UKJA@ukja102>
UKJA@ukja102> set serveroutput on
UKJA@ukja102>
UKJA@ukja102> col sid new_value my_sid
UKJA@ukja102>
UKJA@ukja102> select sid
2 from v$mystat where rownum = 1
3 ;
SID
139
Elapsed: 00:00:00.03
UKJA@ukja102>
UKJA@ukja102> exec print_table('select * from v$lock where sid = &my_sid');
ADDR : 695C4224
KADDR : 695C423C
SID : 139
TYPE : TM
ID1 : 74212
ID2 : 0
LMODE : 3
REQUEST : 0
CTIME : 0
BLOCK : 0
ADDR : 69612444
KADDR : 69612560
SID : 139
TYPE : TX
ID1 : 458787
ID2 : 13053
LMODE : 6
REQUEST : 0
CTIME : 0
BLOCK : 0
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.14DML acquires TX lock in exclusive(6) mode(row level lock) and TM lock in row exclusive(3) mode.
=======================================
Oracle Performance Storyteller
Dion Cho
http://ukja.tistory.com
http://wiki.ex-em.com/index.php/performance_in_depth
http://wiki.ex-em.com/index.php/optimizing_oracle_optimizer
=======================================
Maybe you are looking for
-
Using a JAR file as a project file
My application allows the user to create projects. Previously, a project file was simply an XML file. Now, a project file needs to also contain many images. I thought it would be a good idea to simply use a JAR file as my project file. Since I've rea
-
DSO upload and no data in Active data table
Hi Experts, I have a strange problem.I have loaded data to DSO from DS in BI7. It has the further uplaod to cube.I have activated the DSO and it went sucessfull and had Request ID generated. It has added and transfer records available like 150000 rec
-
Loop though folder in the order of filename
Is there a way in ssis using for each loop container to loop through all the files in the order of file names. for example if I have 1.txt 2.txt 3.txt 4.txt I want to process 1.txt then 2.txt and so on instead of processing 1. txt then 4.txt and then
-
Can I update OS 10.5.8 form my daughters 10.8.5?
Can I update my macbook pro OS with another macs OS
-
Anyone Familiar linking Apache2 Server to Tomcat 5.5?
I am trying to have Apache2 work with Tomcat 5.5, but am having no success. There's about 10,000 documents out on the web that all contradict each other and I have no clue how to do this correctly. Here's what I have and what I am trying to do... OS: