I'm trying to return a result set from a 11g Oracle table, after I've received the set back I need to set all the fetched rows as updated.
The below script returns only one row at a time, and I can't really get the update to work as I like. Some basic explanation would be highly appriciated.
Maybe it's also a bad idea using the rowtype?
CREATE OR REPLACE PROCEDURE OWNER_EXT.X_GETEXTERNALACCOUNTREF(result out X_externalaccountref%rowtype)
IS
cur SYS_REFCURSOR;
BEGIN
open cur for select * from X_externalaccountref WHERE externalstatus IS NULL;
LOOP
FETCH cur INTO result;
update X_externalaccountref set externalstatus = 1, externalchangedate = SYSDATE() where X_id = result.X_id;
EXIT WHEN cur%NOTFOUND;
END LOOP;
close cur;
END;
/
Why you only get one record returned:
You loop over the recordset, fetching one record at a time, and each time you assign this record to the output variable. So only your last record will be stored in the output variable.
What you want to do is return a record set. For this, you can use pl/sql tables. To easily fetch a set into a table you could use bulk collect into (a link - but google will find you a lot more). You can use the rowtype as the type for your table, or a type you make up yourself. You could use a package variable to declare a type, or define a type in the database schema. If you use rowtype, that is not bad at all. If your table should change, then rowtype will reflect this aswell, saving you the hassle of trawling through your code to add or remove columns should you have manually declared each column in a own type.
Ex:
function hand_out_money
return pck_emp.t_tab_emp
is
tab_emp pck_emp.t_tab_emp;
begin
select *
bulk collect into tab_emp
from emp
where deptno = 20;
update emp
set comm = comm + 10
where deptno = 20;
return tab_emp;
end;
To be able to use this, have t_tab_emp declared in a package_spec. This way, you can reference the returned type from where you call this code. Just put type t_tab_emp is table of emp%rowtype; in there - like i would do in package pck_emp.
Your calling code could then be:
declare
tab_result pck.t_tab_emp;
begin
tab_result := hand_out_money;
end;
To do your update:
If you fetch all your record into a plsql table, you could thereafter do a single update statement:
update X_externalaccountref
set externalstatus = 1, externalchangedate = SYSDATE
where externalstatus IS NULL;
Also: you could just use a function if you only return this one variable, it would make sense for a getter.
Also: i generally don't like function or procedures named 'getxxx' who then do DML. More proper would be to call your procedure 'activate_external_accounts' for example, which would then return the recordset. Mind, that if you do a bulk select before the update, the externalstatus and externalchangedate won't be updated! So you don't get a resultset returned, but a pre-update set.
update X_externalaccountref
set externalstatus = 1
, externalchangedate = SYSDATE
where externalstatus is null;
Why not?
Related
I'm working with a vendor's database, and I need to increment a value and return it. I have the right command, it updates the table, but the output in oracle developer just says "PL/SQL procedure successfully completed." How do I return NewReceiptNumber?
DECLARE
NewReceiptNumber int;
BEGIN
UPDATE SYSCODES
SET (VAR_VALUE) = VAR_VALUE+1
WHERE VAR_NAME='LAST_RCPT'
RETURNING VAR_VALUE INTO NewReceiptNumber;
END;
You are just depicting an anonymous block there, to VIEW the value of NewReceiptNumber in that code you'll have to use:
dbms_output.put_line(NewReceiptNumber).
as in:
DECLARE
NewReceiptNumber int;
BEGIN
UPDATE SYSCODES
SET (VAR_VALUE) = VAR_VALUE+1
WHERE VAR_NAME='LAST_RCPT'
RETURNING VAR_VALUE INTO NewReceiptNumber;
dbms_output.put_line(NewReceiptNumber);
END;
But if your intention is to actually return this value to another procedure or a call from your front-end, you'll have to declare a stored procedure and within that declaration indicate your output parameter, something like:
CREATE OR REPLACE PROCEDURE my_proc(newreceiptnumber out INT) AS
BEGIN
UPDATE syscodes
SET (var_value) = var_value+1
WHERE var_name='LAST_RCPT'
RETURNING var_value INTO newreceiptnumber;
END my_proc;
And of course it'll be a more robust solution if you send your updated values as parameters as well, this is just the minimal approach.
I am trying to execute my below procedure but kept getting error (ORA-00900: invalid SQL statement)
CREATE OR REPLACE PROCEDURE RESETUSERSESSION (run IN VARCHAR2)
IS
cursor usersessiondetail_cur IS
SELECT usd.CLIENTID,usd.OPERID,usd.REGISTER,usd.MACHINE_ID,usd.SESSIONNUMBER
FROM cashiering_dev.CSH_USER usr, cashiering_dev.CSH_USERSESSIONDETAIL usd
WHERE usr.clientid = usd.clientid
AND usr.operid = usd.operid
AND usr.register = usd.register
AND usr.machine_id = usd.machine_id
AND usr.sessionnumber = usd.sessionnumber
AND usr.Machine_ID = 'basrytest'
AND usd.LOGOFFDATETIME IS NULL;
BEGIN
OPEN usersessiondetail_cur;
FOR vItems in usersessiondetail_cur
LOOP
EXECUTE IMMEDIATE 'UPDATE csh_UserSessionDetail
SET ClientID =vItems.CLIENTID
WHERE ClientID =vItems.CLIENTID
AND OperID =vItems.OPERID
AND Register =vItems.REGISTER
AND Machine_ID =vItems.MACHINE_ID
AND SessionNumber =vItems.SESSIONNUMBER';
END LOOP;
CLOSE usersessiondetail_cur;
END;
Your SQL is invalid because the cursor projection names are not in scope when the dynamic SQL string is executed. You need to use placeholders like this:
FOR vItems in usersessiondetail_cur
LOOP
EXECUTE IMMEDIATE 'UPDATE csh_UserSessionDetail
SET ClientID = :p1
WHERE ClientID = :p2
AND OperID = :p3
AND Register = :p4
AND Machine_ID = :p5
AND SessionNumber = :p6'
using vItems.CLIENTID
, vItems.CLIENTID
, vItems.OPERID
, Items.REGISTER
, vItems.MACHINE_ID
, vItems.SESSIONNUMBER;
END LOOP;
Your dynamic code is not an anonymous PL/SQL block or a CALL statement so parameters are passed by position not name, which means you must pass vItems.CLIENTID twice. Find out more.
Other observations
First and foremost, there is absolutely no need to implement dynamic execution for this SQL.
The OPEN and CLOSE cursor statements are not used with a FOR cursor loop.
You do not need an explicit cursor declaration for this query.
The row-by-agonising row UPDATE with a cursor loop is bad practice and needlessly inefficient compared to set-based UPDATE statement.
Your procedure doesn't use the run parameter ...
... but the cursor does have a hardcoded string for MACHINE_ID.
Lastly, the UPDATE statement doesn't actually change the state of the table, because it sets CLIENT_ID = CLIENT_ID, so the whole procedure is pointless.
Apart from that, everything is fine.
I assume you're writing this as a test for understanding how to use dynamic SQL rather than as an implementation of business logic. But even if it is a test it is better to write a proper piece of code which does something. Especially when you're sharing the code with others on StackOverflow. Posting code with so many issues is distracting because potential respondents don't know which to tackle.
A much simpler approach with just FOR loop. We dont require to Open Close cursor in this case as this is internally handled by Oracle. Also I do not understand the need of updating Client ID again. If we are selecting the Client ID in where Clause there is no significance of Updating. Anyhow Enjoy :)
CREATE OR REPLACE
PROCEDURE RESETUSERSESSION(
run IN VARCHAR2)
AS
BEGIN
FOR vItems IN
(SELECT usd.CLIENTID,
usd.OPERID,
usd.REGISTER,
usd.MACHINE_ID,
usd.SESSIONNUMBER
FROM cashiering_dev.CSH_USER usr,
cashiering_dev.CSH_USERSESSIONDETAIL usd
WHERE usr.clientid = usd.clientid
AND usr.operid = usd.operid
AND usr.register = usd.register
AND usr.machine_id = usd.machine_id
AND usr.sessionnumber = usd.sessionnumber
AND usr.machine_id = 'basrytest'
AND usd.LOGOFFDATETIME IS NULL
)
LOOP
UPDATE csh_UserSessionDetail
SET ClientID =vItems.CLIENTID
WHERE ClientID =vItems.CLIENTID
AND OperID =vItems.OPERID
AND Register =vItems.REGISTER
AND Machine_ID =vItems.MACHINE_ID
AND SessionNumber =vItems.SESSIONNUMBER;
END LOOP;
END;
/
I have one simple update statement inside oracle stored procedure. Its executing successfully but its not updating the table.
CREATE OR REPLACE PROCEDURE UpdateSourceLog
( SourceLogId IN NUMBER, TotalRowCount IN INT,Status IN VARCHAR)
AS
BEGIN
UPDATE SourceLog
SET Status = Status,
TotalRowCount = TotalRowCount,
EndTime = SYSDATE
WHERE SourceLogId = SourceLogId;
COMMIT;
END;
I have tried with changing the perameter name different from column name. Then also Its not working.
And I have tried with anonymous block. I'm not able to find out the isue. Please help me in this regard.
Thanks!
It is a bad practice to give parameters the same name as table columns.
So you should change it:
CREATE OR REPLACE PROCEDURE UpdateSourceLog
( p_SourceLogId IN NUMBER, p_TotalRowCount IN INT,p_status IN VARCHAR)
AS
BEGIN
UPDATE SourceLog
SET Status = p_status,
TotalRowCount = p_TotalRowCount,
EndTime = SYSDATE
WHERE SourceLogId = p_SourceLogId;
COMMIT;
END;
Because for now, most likely, Oracle understands it as column names and just update column to value from this column (no sense at all)
I am making an oracle function that sync values between two tables and My intention is to show a string that show how many rows affected and displays it when user execute the function.
my function creation is like this
CREATE OR REPLACE FUNCTION WELTESADMIN.DUM_MST_SYNC(PROJNAME IN VARCHAR2)
RETURN NUMBER IS NUM_ROWS NUMBER;
BEGIN
MERGE INTO MASTER_DRAWING DST
USING (SELECT WEIGHT_DUM, HEAD_MARK_DUM FROM DUMMY_MASTER_DRAWING) SRC
ON (DST.HEAD_MARK = SRC.HEAD_MARK_DUM)
WHEN MATCHED THEN UPDATE SET DST.WEIGHT = SRC.WEIGHT_DUM
WHERE DST.PROJECT_NAME = SRC.PROJECT_NAME_DUM
AND DST.PROJECT_NAME = PROJNAME;
dbms_output.put_line( sql%rowcount || ' rows merged' );
END;
if i execute the begin part in the TOAD or SQL Developer i can see how many rows affected. My target is to collect this function into a procedure and when user wants to sync tables they just need to run the procedure with PROJNAME value supplied for specific project.
Please help me on how to improve this code,
Best regards
You can use SQL%ROWCOUNT to get the number of rows affected by the MERGE. Add the following statement in your code immediately after the MERGE :
dbms_output.put_line( sql%rowcount || ' rows merged' );
To return this value, declare a NUMBER variable and assign the sql%rowcount value to it. And then return that value. Something like :
Function
.......
Return NUMBER
.......
num_rows NUMBER;
......
Begin
Merge....
num_rows := SQL%ROWCOUNT;
RETURN num_rows;
END;
And, you don't need a procedure to execute the function. You can execute in SQL :
select function(project_name)
from dual
/
Update Since OP is trying to use DML inside a function, need to make it autonomous transaction to be able to perform DML without raising the ORA-14551.
You could use the directive pragma autonomous_transaction. This will run the function into an independent transaction that will be able to perform DML without raising the ORA-14551. However, remember, the results of the DML will be committed outside of the scope of the parent transaction. If you have only single transaction, you could use the workaround that I suggested. Add, PRAGMA AUTONOMOUS_TRANSACTION; immediately after the RETURN statement before BEGIN.
CREATE OR REPLACE
FUNCTION WELTESADMIN.DUM_MST_SYNC(
PROJNAME IN VARCHAR2)
RETURN NUMBER
IS
num_rows NUMBER;
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
MERGE INTO MASTER_DRAWING DST USING
(SELECT WEIGHT_DUM, HEAD_MARK_DUM FROM DUMMY_MASTER_DRAWING
) SRC ON (DST.HEAD_MARK = SRC.HEAD_MARK_DUM)
WHEN MATCHED THEN
UPDATE
SET DST.WEIGHT = SRC.WEIGHT_DUM
WHERE DST.PROJECT_NAME = SRC.PROJECT_NAME_DUM
AND DST.PROJECT_NAME = PROJNAME;
num_rows := SQL%ROWCOUNT;
COMMIT;
RETURN num_rows;
END;
/
I have a query inside the function with RESULT_CACHE.
So when the table is changed - my cache is invalidated and function is executed again.
What I want is to implement the function that depends only on input parameters, and doesn't depend on any implicit dependencies (like tables, etc).
Is it possible (without dynamic sql)?
a function that depends only on its parameters can be declared DETERMINISTIC. The results of this function will be cached in some cases. This thread on the OTN forums shows how deterministic function results get cached inside SQL statements.
As of 10gR2, the function results don't get cached across SQL statements nor do they get cached in PL/SQL. Still, this cache feature can be useful if you call a function in a SELECT where it might get called lots of time.
I don't have a 11gR2 instance available right now, so I can't test the RESULT_CACHE feature, but have you considered delaring your function relying on a fixed dummy table (a table that never gets updated for instance)?
The correct answer is NO.
A solution in cases where things like result caches and materialized views won't work because of invalidations or too much overhead is the Oracle In-Memory Database Cache option. See result caches ..... what about heavily modified data It's a real smart option, not cheap.
If you use a database link it is possible to create a function result cache that will read from a table when a parameter changes but will not be invalidated when the table changes.
Obviously there are some issues with this approach; performance (even for a self-link), maintenance, the function may return the wrong result, everybody hates database links, etc.
Note that RELIES_ON is deprecated in 11gR2. Dependencies are automatically determined at run-time, even dynamic SQL wouldn't help you here. But apparently this dependency tracking doesn't work over database links.
The script below demonstrates how this works. Remove "#myself" from the function to see how it normally works. Some of the code is based on this great article.
--For testing, create a package that will hold a counter.
create or replace package counter is
procedure reset;
procedure increment;
function get_counter return number;
end;
/
create or replace package body counter as
v_counter number := 0;
procedure reset is begin v_counter := 0; end;
procedure increment is begin v_counter := v_counter + 1; end;
function get_counter return number is begin return v_counter; end;
end;
/
--Create database link
create database link myself connect to <username> identified by "<password>"
using '<connect string>';
drop table test purge;
create table test(a number primary key, b varchar2(100));
insert into test values(1, 'old value1');
insert into test values(2, 'old value2');
commit;
--Cached function that references a table and keeps track of the number of executions.
drop function test_cache;
create or replace function test_cache(p_a number) return varchar2 result_cache is
v_result varchar2(100);
begin
counter.increment;
select b into v_result from test#myself where a = p_a;
return v_result;
end;
/
--Reset
begin
counter.reset;
end;
/
--Start with 0 calls
select counter.get_counter from dual;
--First result is "value 1", is only called once no matter how many times it runs.
select test_cache(1) from dual;
select test_cache(1) from dual;
select test_cache(1) from dual;
select counter.get_counter from dual;
--Call for another parameter, counter only increments by 1.
select test_cache(2) from dual;
select test_cache(2) from dual;
select test_cache(2) from dual;
select counter.get_counter from dual;
--Now change the table. This normally would invalidate the cache.
update test set b = 'new value1' where a = 1;
update test set b = 'new value2' where a = 2;
commit;
--Table was changed, but old values are still used. Counter was not incremented.
select test_cache(1) from dual;
select test_cache(2) from dual;
select counter.get_counter from dual;
--The function is not dependent on the table.
SELECT ro.id AS result_cache_id
, ro.name AS result_name
, do.object_name
FROM v$result_cache_objects ro
, v$result_cache_dependency rd
, dba_objects do
WHERE ro.id = rd.result_id
AND rd.object_no = do.object_id;
Two options:
Don't query any table.
Implement your own cache - wrap the function in a package, and store the query results in a PL/SQL table in memory. The downside to this approach, however, is that the cache only works within a single session. Each session will maintain its own cache.