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:
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:
To do your update:
If you fetch all your record into a plsql table, you could thereafter do a single update statement:
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.