Declaring a cursor in an Anonymous Block
How do I declare a cursor in an Anonymous Block? I've looked in several sources and haven't found anything that explains this.
Does anyone have a link to where this would be explained?
Thanks
Depends on whether you're talking about an explicit or an implicit cursor, but it's basically the same way you declare either in a non-anonymous block, i.e.
DECLARE
CURSOR cursor_name IS ...
BEGIN
END;or
BEGIN
FOR x IN (SELECT ... )
LOOP
END LOOP;
END;Justin
Similar Messages
-
INVALID CURSOR - Anonymous Block calling Cursor in function
I am getting an error when trying to call my cursor.
CREATE OR REPLACE PACKAGE tax_update
AS
TYPE gencur IS ref cursor;
FUNCTION tax_sf
p_state IN bb_tax.state%type,
p_thecursor IN OUT gencur
RETURN NUMBER;
END;
CREATE OR REPLACE PACKAGE BODY tax_update
AS
FUNCTION tax_sf
p_state IN bb_tax.state%type,
p_thecursor IN OUT gencur
RETURN NUMBER
IS
lv_taxrate NUMBER;
BEGIN
OPEN p_thecursor FOR
SELECT taxrate
FROM bb_tax
WHERE state = p_state;
RETURN lv_taxrate;
END;
END;
DECLARE
tax_cur tax_update.gencur;
rec_tax bb_tax%rowtype;
BEGIN
LOOP
FETCH tax_cur INTO rec_tax;
EXIT WHEN tax_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(rec_tax.taxrate);
END LOOP;
END;
DECLARE
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 6Assignment is to create a package that will hold tax rates by state in a packaged cursor. The package will contain a function that can receive a 2 character state abbr. as an argument and find a match in the cursor and return the tax rate for tha tstate. An anonymous block will test the function with state of NC.
Can anyone assist?You would need to call the function to open the cursor before you try to fetch from the cursor
DECLARE
tax_cur tax_update.gencur;
rec_tax bb_tax%rowtype;
l_some_number number;
BEGIN
l_some_number := tax_update.tax_sf( <<some state parameter>>, tax_cur );
LOOP
FETCH tax_cur INTO rec_tax;
EXIT WHEN tax_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(rec_tax.taxrate);
END LOOP;
END;A couple of points, though.
1) Your function returns a NUMBER but that NUMBER will always be NULL. It seems rather unlikely that this is really what you want. It would seem to make more sense for the function to return the cursor rather than returning a superfluous number.
2) Your function requires a `bb_tax.state%type` parameter. But your anonymous block doesn't seem to have any concept of a state so I'm not sure what you want to pass in there.
3) Looking at the code, it seems a bit odd that your cursor returns a single column of data. If a state can have multiple rates, wouldn't you need to select some additional criteria in order to figure out which sort of tax each row represents or to otherwise differentiate different rows? If a state can only have a single tax rate, it makes no sense to open a cursor that is only going to ever return a single row.
4) There is no need to declare your own weak ref cursor type (tax_update.gencur). You can just use the Oracle built-in type SYS_REFCURSOR.
Justin -
How to declare in anonymous block
Declare
CURSOR c_je2acct_othr
IS
SELECT j.jemq_num, j.ml_retail_account,
-- (CASE WHEN j.exer_type = 4 THEN j.sar_shares ELSE j.shares END) shares, -- removed * -1 from sar_shares Manu 12/02/04
/* Commented 02/01/07*/
(CASE WHEN j.exer_type = 4 THEN
fn_get_shares(u.user_id,u.exer_num,u.soc_sec,j.
sar_shares)
ELSE (case when u.exer_type=2 and u.opts_exer!=u.shrs_sold and j.shares=u.shrs_sold then 0 else j.shares end)
END) shares,
-- removed * -1 from sar_shares Manu 12/02/04
j.name_first,
j.name_last, j.exer_type, j.ml_sec_num, j.ivr_plan_num,
j.exer_dt, j.grant_dt, j.user_id, j.mlu_rowid, j.settle_dt,
j.exer_num, j.plan_type, j.grant_num, j.acct_num_othr,
j.add_cancel,
/* (CASE WHEN j.exer_type = 4 THEN j.sar_cash_amount * -1 -- turned negative Manu 12/02/04 ml_retail distr
commented the above line for calculation of proceeds into other account for sar sale.
(CASE WHEN j.exer_type = 4 THEN
Pk_Xop_Citibank_Forex.fn_get_netamount(u.user_id,u.
exer_num,u.soc_sec,
u.sar_cash_amount,NVL(u.comm_value, 0),
NVL(u.tot_fee, 0),
NVL(u.multi_curr_handling_fee, 0))
-- Removed the negative as on ml_exer_upload all values are +ve.
ELSE
( (DECODE(u.exer_type,0,u.opts_exer * u.mkt_prc,u.shrs_sold * u.mkt_prc
- ( ROUND((u.opts_exer * NVL (u.opt_prc, 0)),2)
-- SPIF 39060 Added a Round of condition.
+ DECODE (NVL (u.shrs_wthld_for_taxes, 'N'),
'Y', 0,
ROUND (u.tot_tax, 2)
+ u.tot_fee
+ NVL(u.multi_curr_handling_fee,0)
+ u.comm_value
- u.backup_withholding
END ) AS gl_amt,
T.je_othr_mlacct_jemsg AS vc_trailer_desc,
u.opts_exer ,
u.shrs_sold,
u.rsu_type
FROM TB_XOP_JEMQ j, TB_ML_EXER_UPLOAD u, TB_FC_COMPY T
WHERE j.q_flag = 'N' AND u.je_flag = 'Y'
AND j.entry_dttime >= TRUNC (SYSDATE)
AND j.entry_dttime < TRUNC (SYSDATE) +1
AND j.source = 'X'
AND j.acct_num_othr != ' '
and (case when u.exer_type=2 and u.opts_exer!=u.shrs_sold then (case when j.shares=u.shrs_sold then 0 else 1 end) else 1 end)=1 FIx for PCTUP00566081
AND ( disp_flag <> 'D' OR disp_flag IS NULL ) Added by MARAN ARUNACHALAM on 01/25/2011 for PCTUP00493542 Fix
and j.current_status = '2Q' removed not required now in new plan
AND NOT EXISTS (
SELECT 1
FROM TB_XOP_JEMQ j2
WHERE j2.prev_jemq = j.jemq_num
AND source = 'T'
AND j.add_cancel = j2.add_cancel
AND j.user_id = j2.user_id
AND j.exer_num = j2.exer_num)
AND j.mlu_rowid = u.ROWID
AND 'CMS'||T.compy_acronym||'_USER' = j.user_id
ORDER BY add_cancel DESC;
v_mlac_mesg VARCHAR2(1000);
-- JE_OTHR_MLACCT_JEMSG
BEGIN
dbms_output.put_line('success');
FOR v_je2acct_othr IN c_je2acct_othr
LOOP
dbms_output.put_line('success1');
BEGIN
dbms_output.put_line('success2');
IF v_je2acct_othr.add_cancel = 'C'
THEN
dbms_output.put_line('success3');
UPDATE TB_XOP_JEMQ
SET add_cancel = DECODE(current_status,
'RJ',
add_cancel,
'C'),
q_flag = DECODE(current_status, 'RJ', q_flag, 'N'),
activ_dt = DECODE(current_status,
'RJ',
activ_dt,
SYSDATE)
WHERE prev_jemq = v_je2acct_othr.jemq_num
AND user_id = v_je2acct_othr.user_id
AND exer_num = v_je2acct_othr.exer_num
AND source ='T';
dbms_output.put_line('success4');
ELSIF v_je2acct_othr.add_cancel = 'A'
THEN
dbms_output.put_line('success5');
-- manipulating amount and shares to transfer when different exercise types
v_je2acct_othr.gl_amt :=( CASE
WHEN v_je2acct_othr.exer_type = 0 THEN 0
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer
!= v_je2acct_othr.shrs_sold
THEN v_je2acct_othr.gl_amt
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer =
v_je2acct_othr.shrs_sold
THEN v_je2acct_othr.gl_amt
ELSE v_je2acct_othr.gl_amt
END );
---- Commented on 11/01/2006 For Fixing 30585
/* v_je2acct_othr.shares :=( CASE
WHEN v_je2acct_othr.exer_type = 0 THEN v_je2acct_othr.opts_exer
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer != v_je2acct_othr.shrs_sold
THEN v_je2acct_othr.opts_exer - v_je2acct_othr.shrs_sold
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer = v_je2acct_othr.shrs_sold
THEN 0
ELSE v_je2acct_othr.shares
END );*/
---- Commented on 11/01/2006 For Fixing 30585
v_je2acct_othr.shares :=( CASE
WHEN v_je2acct_othr.exer_type = 0 THEN v_je2acct_othr.
Shares
--- Replaced opts_exer with the Shares amount from the previous journal for fixing 30585
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer
!= v_je2acct_othr.shrs_sold and v_je2acct_othr.shares!=0 and v_je2acct_othr.plan_type <> 0 -- Added plantype condition for CQ:PCTUP00493542
THEN v_je2acct_othr.Shares - v_je2acct_othr.shrs_sold
--- Replaced opts_exer with the Shares amount from the previous journal for fixing 30585
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer =
v_je2acct_othr.shrs_sold
THEN 0
ELSE v_je2acct_othr.shares
END );
dbms_output.put_line('success6');
IF LENGTH(TRIM(v_je2acct_othr.acct_num_othr))=8 OR TRIM(v_je2acct_othr.acct_num_othr) IS NULL
THEN
v_mlac_mesg :=NULL;
ELSE
v_mlac_mesg :='Check the ml a/c length';
dbms_output.put_line('success7');
END IF;
INSERT INTO TB_XOP_JEMQ
(jemq_num,
prev_jemq,
ml_retail_account,
wcma_shares,
shares, wcma_taxes, tax_amt,
wcma_reimburse,
reimburse_amt,
name_first,
name_last, exer_type,
ml_sec_num, wcma_bulking, bulking_amt,
ivr_plan_num,
exer_dt, grant_dt,
user_id, source,
mlu_rowid, settle_dt,
exer_num, plan_type,
grant_num,
vc_trailer_desc, rsu_type
VALUES (Pk_Xop_Get_Jemqnum.fn_xop_get_jemqnum,
v_je2acct_othr.jemq_num,
v_je2acct_othr.acct_num_othr,
-- 2nd ml_retail_account,
v_je2acct_othr.ml_retail_account,
-- move shares from old acct to 2nd acct above
v_je2acct_othr.shares,
--this is SHARES
--wcma_taxes
0,
--tax_amt,
v_je2acct_othr.ml_retail_account,
-- move gl_amt from old acct to 2nd acct above
v_je2acct_othr.gl_amt * -1,
v_je2acct_othr.name_first,
v_je2acct_othr.name_last, v_je2acct_othr.
exer_type,
v_je2acct_othr.ml_sec_num, ' ',
--wcma_bulking,
0,
--bulking_amt,
v_je2acct_othr.ivr_plan_num,
v_je2acct_othr.exer_dt, v_je2acct_othr.
grant_dt,
v_je2acct_othr.user_id, 'T',
--source
v_je2acct_othr.mlu_rowid, v_je2acct_othr.
settle_dt,
v_je2acct_othr.exer_num, v_je2acct_othr.
plan_type,
v_je2acct_othr.grant_num,
v_je2acct_othr.vc_trailer_desc,
v_je2acct_othr.
rsu_type
dbms_output.put_line('success8');
END IF;
EXCEPTION
WHEN OTHERS
THEN
Pr_Xop_Log_Errors ( 'Code :'
|| NVL(v_mlac_mesg,SQLERRM)
|| ' at '
|| USER
|| 'at sub exec block in pop_je2acct_othr'
END;
dbms_output.put_line('success9'); -- end of begin within loop
END LOOP;
--COMMIT;
EXCEPTION
WHEN OTHERS
THEN
Pr_Xop_Log_Errors ( 'Code :'
|| NVL(v_mlac_mesg,SQLERRM)
|| ' at '
|| USER
|| 'at pk_xop_jemq.pop_je2acct_othr'
dbms_output.put_line('success10');
END;}
{ORA-06550: line 10, column 31:
PL/SQL: ORA-00904: "FN_GET_SHARES": invalid identifier
ORA-06550: line 6, column 11:
PL/SQL: SQL Statement ignored
ORA-06550: line 81, column 17:
PLS-00364: loop index variable 'V_JE2ACCT_OTHR' use is invalid
ORA-06550: line 81, column 14:
PL/SQL: Statement ignored}
HI friends, as i am getting two errors when running code in the anonymous block, then how to declare that 2 errors in declare section plz guide me}Noone, will read your code unless it is formatted like below. See the comments added
DECLARE
CURSOR c_je2acct_othr
IS
SELECT j.jemq_num,
j.ml_retail_account,
-- (CASE WHEN j.exer_type = 4 THEN j.sar_shares ELSE j.shares END) shares, -- removed * -1 from sar_shares Manu 12/02/04
/* Commented 02/01/07*/
CASE
WHEN j.exer_type = 4
--"The current user is not seeing the below function fn_get_shares.Privilege issue probably.
THEN fn_get_shares(u.user_id,u.exer_num,u.soc_sec,j. sar_shares)
ELSE (
CASE
WHEN u.exer_type=2
AND u.opts_exer!=u.shrs_sold
AND j.shares =u.shrs_sold
THEN 0
ELSE j.shares
END)
END) shares,
-- removed * -1 from sar_shares Manu 12/02/04
j.name_first,
j.name_last,
j.exer_type,
j.ml_sec_num,
j.ivr_plan_num,
j.exer_dt,
j.grant_dt,
j.user_id,
j.mlu_rowid,
j.settle_dt,
j.exer_num,
j.plan_type,
j.grant_num,
j.acct_num_othr,
j.add_cancel,
/* (CASE WHEN j.exer_type = 4 THEN j.sar_cash_amount * -1 -- turned negative Manu 12/02/04 ml_retail distr
commented the above line for calculation of proceeds into other account for sar sale.
CASE
WHEN j.exer_type = 4
THEN Pk_Xop_Citibank_Forex.fn_get_netamount(u.user_id,u. exer_num,u.soc_sec, u.sar_cash_amount,NVL(u.comm_value, 0), NVL(u.tot_fee, 0), NVL(u.multi_curr_handling_fee, 0))
-- Removed the negative as on ml_exer_upload all values are +ve.
ELSE ( (DECODE(u.exer_type,0,u.opts_exer * u.mkt_prc,u.shrs_sold * u.mkt_prc )) - ( ROUND((u.opts_exer * NVL (u.opt_prc, 0)),2)
-- SPIF 39060 Added a Round of condition.
+ DECODE (NVL (u.shrs_wthld_for_taxes, 'N'), 'Y', 0, ROUND (u.tot_tax, 2) ) + u.tot_fee + NVL(u.multi_curr_handling_fee,0) + u.comm_value ) - u.backup_withholding )
END ) AS gl_amt,
T.je_othr_mlacct_jemsg AS vc_trailer_desc,
u.opts_exer ,
u.shrs_sold,
u.rsu_type
FROM TB_XOP_JEMQ j,
TB_ML_EXER_UPLOAD u,
TB_FC_COMPY T
WHERE j.q_flag = 'N'
AND u.je_flag = 'Y'
AND j.entry_dttime >= TRUNC (SYSDATE)
AND j.entry_dttime < TRUNC (SYSDATE) +1
AND j.source = 'X'
AND j.acct_num_othr != ' '
--and (case when u.exer_type=2 and u.opts_exer!=u.shrs_sold then (case when j.shares=u.shrs_sold then 0 else 1 end) else 1 end)=1 -- FIx for PCTUP00566081
--AND ( disp_flag <> 'D' OR disp_flag IS NULL ) -- Added by MARAN ARUNACHALAM on 01/25/2011 for PCTUP00493542 Fix
--and j.current_status = '2Q' -- removed not required now in new plan
AND NOT EXISTS
(SELECT 1
FROM TB_XOP_JEMQ j2
WHERE j2.prev_jemq = j.jemq_num
AND source = 'T'
AND j.add_cancel = j2.add_cancel
AND j.user_id = j2.user_id
AND j.exer_num = j2.exer_num
AND j.mlu_rowid = u.ROWID
AND 'CMS'
||T.compy_acronym
||'_USER' = j.user_id
ORDER BY add_cancel DESC;
v_mlac_mesg VARCHAR2(1000);
-- JE_OTHR_MLACCT_JEMSG
BEGIN
dbms_output.put_line('success');
FOR v_je2acct_othr IN c_je2acct_othr
LOOP
dbms_output.put_line('success1');
BEGIN
dbms_output.put_line('success2');
IF v_je2acct_othr.add_cancel = 'C' THEN
dbms_output.put_line('success3');
UPDATE TB_XOP_JEMQ
SET add_cancel = DECODE(current_status, 'RJ', add_cancel, 'C'),
q_flag = DECODE(current_status, 'RJ', q_flag, 'N'),
activ_dt = DECODE(current_status, 'RJ', activ_dt, SYSDATE)
WHERE prev_jemq = v_je2acct_othr.jemq_num
AND user_id = v_je2acct_othr.user_id
AND exer_num = v_je2acct_othr.exer_num
AND source ='T';
dbms_output.put_line('success4');
ELSIF v_je2acct_othr.add_cancel = 'A' THEN
dbms_output.put_line('success5');
-- manipulating amount and shares to transfer when different exercise types
--"You cannot assign values to the recor variable declared for a loop. Either define seperate variables or use explicit record variable"
v_je2acct_othr.gl_amt :=
CASE
WHEN v_je2acct_othr.exer_type = 0 THEN
0
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer != v_je2acct_othr.shrs_sold THEN
v_je2acct_othr.gl_amt
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer = v_je2acct_othr.shrs_sold THEN
v_je2acct_othr.gl_amt
ELSE
v_je2acct_othr.gl_amt
END );
---- Commented on 11/01/2006 For Fixing 30585
/* v_je2acct_othr.shares :=( CASE
WHEN v_je2acct_othr.exer_type = 0 THEN v_je2acct_othr.opts_exer
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer != v_je2acct_othr.shrs_sold
THEN v_je2acct_othr.opts_exer - v_je2acct_othr.shrs_sold
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer = v_je2acct_othr.shrs_sold
THEN 0
ELSE v_je2acct_othr.shares
END );*/
---- Commented on 11/01/2006 For Fixing 30585
v_je2acct_othr.shares :=
CASE
WHEN v_je2acct_othr.exer_type = 0 THEN
v_je2acct_othr. Shares
--- Replaced opts_exer with the Shares amount from the previous journal for fixing 30585
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer != v_je2acct_othr.shrs_sold AND v_je2acct_othr.shares!=0 AND v_je2acct_othr.plan_type 0 -- Added plantype condition for CQ:PCTUP00493542
THEN
v_je2acct_othr.Shares - v_je2acct_othr.shrs_sold
--- Replaced opts_exer with the Shares amount from the previous journal for fixing 30585
WHEN v_je2acct_othr.exer_type = 2 AND v_je2acct_othr.opts_exer = v_je2acct_othr.shrs_sold THEN
0
ELSE
v_je2acct_othr.shares
END );
dbms_output.put_line('success6');
IF LENGTH(TRIM(v_je2acct_othr.acct_num_othr))=8 OR TRIM(v_je2acct_othr.acct_num_othr) IS NULL THEN
v_mlac_mesg :=NULL;
ELSE
v_mlac_mesg :='Check the ml a/c length';
dbms_output.put_line('success7');
END IF;
INSERT
INTO TB_XOP_JEMQ
jemq_num,
prev_jemq,
ml_retail_account,
wcma_shares,
shares,
wcma_taxes,
tax_amt,
wcma_reimburse,
reimburse_amt,
name_first,
name_last,
exer_type,
ml_sec_num,
wcma_bulking,
bulking_amt,
ivr_plan_num,
exer_dt,
grant_dt,
user_id,
source,
mlu_rowid,
settle_dt,
exer_num,
plan_type,
grant_num,
vc_trailer_desc,
rsu_type
VALUES
Pk_Xop_Get_Jemqnum.fn_xop_get_jemqnum,
v_je2acct_othr.jemq_num,
v_je2acct_othr.acct_num_othr,
-- 2nd ml_retail_account,
v_je2acct_othr.ml_retail_account,
-- move shares from old acct to 2nd acct above
v_je2acct_othr.shares,
--this is SHARES
--wcma_taxes
0,
--tax_amt,
v_je2acct_othr.ml_retail_account,
-- move gl_amt from old acct to 2nd acct above
v_je2acct_othr.gl_amt * -1,
v_je2acct_othr.name_first,
v_je2acct_othr.name_last,
v_je2acct_othr. exer_type,
v_je2acct_othr.ml_sec_num,
--wcma_bulking,
0,
--bulking_amt,
v_je2acct_othr.ivr_plan_num,
v_je2acct_othr.exer_dt,
v_je2acct_othr. grant_dt,
v_je2acct_othr.user_id,
'T',
--source
v_je2acct_othr.mlu_rowid,
v_je2acct_othr. settle_dt,
v_je2acct_othr.exer_num,
v_je2acct_othr. plan_type,
v_je2acct_othr.grant_num,
v_je2acct_othr.vc_trailer_desc,
v_je2acct_othr. rsu_type
dbms_output.put_line('success8');
END IF;
EXCEPTION
WHEN OTHERS THEN
Pr_Xop_Log_Errors ( 'Code :' || NVL(v_mlac_mesg,SQLERRM) || ' at ' || USER || 'at sub exec block in pop_je2acct_othr' );
END;
dbms_output.put_line('success9'); -- end of begin within loop
END LOOP;
--COMMIT;
EXCEPTION
WHEN OTHERS THEN
Pr_Xop_Log_Errors ( 'Code :' || NVL(v_mlac_mesg,SQLERRM) || ' at ' || USER || 'at pk_xop_jemq.pop_je2acct_othr' );
dbms_output.put_line('success10');
END;
{code}   -
Cursor query works in anonymous block but not in procedure
Hello,
My cursor query works fine in anonymous blcok but fails in pl/sql block.
Anonymous block:
declare
cursor c1 is
select object_name
from all_objects
where owner='IRIS_DATA'
and object_type='SEQUENCE';
v_string varchar2(2000);
begin
for c2 in c1 loop
v_string := 'DROP SEQUENCE IRIS_DATA.'||c2.object_name;
execute immediate v_string;
end loop;
commit;
exception
when others then
dbms_output.put_line('Exception :'||sqlerrm);
end;
works fine.
but inside the procedure the it doesn't go inside the cursor loop
procedure get_sequence is
l_dp_handle NUMBER;
v_job_state varchar2(4000);
l_last_job_state VARCHAR2(30) := 'UNDEFINED';
l_job_state VARCHAR2(30) := 'UNDEFINED';
l_sts KU$_STATUS;
v_logs ku$_LogEntry;
v_row PLS_INTEGER;
v_string1 varchar2(2000);
cursor seq_obj is
select object_name
from all_objects
where owner='IRIS_DATA'
and object_type='SEQUENCE';
begin
log_status('get_sequence started.');
--Cursor records to drop the sequences before importing.
for seq_obj_rec in seq_obj loop
log_status('get_sequence: Dropping sequence started.');
v_string1 := 'DROP SEQUENCE IRIS_DATA.'||seq_obj_rec.object_name;
execute immediate v_string1;
end loop;
log_status('get_sequence: Dropping sequence completed.');
exception
WHEN OTHERS THEN
log_status('get_sequence: exception.');
end get_sequence;
it's not going into the seq_obj_rec cursor.
I granted select on all_objects to the user.this user is also having the DBA role as well.
Please advice.PROCEDURE Get_sequence
IS
l_dp_handle NUMBER;
v_job_state VARCHAR2(4000);
l_last_job_state VARCHAR2(30) := 'UNDEFINED';
l_job_state VARCHAR2(30) := 'UNDEFINED';
l_sts KU$_STATUS;
v_logs KU$_LOGENTRY;
v_row PLS_INTEGER;
v_string1 VARCHAR2(2000);
CURSOR seq_obj IS
SELECT object_name
FROM all_objects
WHERE owner = 'IRIS_DATA'
AND object_type = 'SEQUENCE';
BEGIN
Log_status('get_sequence started.');
--Cursor records to drop the sequences before importing.
FOR seq_obj_rec IN seq_obj LOOP
Log_status('get_sequence: Dropping sequence started.');
v_string1 := 'DROP SEQUENCE IRIS_DATA.'
||seq_obj_rec.object_name;
EXECUTE IMMEDIATE v_string1;
END LOOP;
Log_status('get_sequence: Dropping sequence completed.');
EXCEPTION
WHEN OTHERS THEN
Log_status('get_sequence: exception.');
END get_sequence; How do I ask a question on the forums?
SQL and PL/SQL FAQ
scroll down to #9 & use tags in the future. -
Ref cursor from anonymous block
I have no problem to get a ref cursor from a Fill method call with an anonymous pl/sql block. But if my anonymous block contains a DECLARE section, the dataset is not populated.
ex:
BEGIN OPEN :cuInscription FOR SELECT column FROM table; END;
is ok but with
DECLARE A NUMBER; BEGIN OPEN :cuInscription FOR SELECT column FROM table; END;
the dataset is not populated (even if the SQL CALL succeed).
Do you know about that?This issue has been fixed in the ODP.NET 92040 release.
-
PL/SQL Anonymous Block - Trying to Call Function within Cursor
Hello -
I need to create an anonymous block that contains a cursor and a function. I want to call the function from within the cursor, and the function will basically take an ID as its IN parameter, and will return a comma separated list of values.
However, when I try to do this I get the error " function 'GET_PAYMENT_DATES' may not be used in SQL".
Does anyone know of a workaround? I'm trying to avoid having to store this function.
Thanks,
ChristineExploring Keith's suggestion of using the function code inline in your SQL:
test@ORA10G>
test@ORA10G> --
test@ORA10G> drop table t;
Table dropped.
test@ORA10G> drop table monetary_trans;
Table dropped.
test@ORA10G>
test@ORA10G> create table monetary_trans as
2 select 1 household_id, trunc(sysdate)-10 received_date from dual union all
3 select 1, trunc(sysdate)-9 from dual union all
4 select 1, trunc(sysdate)-8 from dual union all
5 select 2, trunc(sysdate)-7 from dual union all
6 select 2, trunc(sysdate)-6 from dual;
Table created.
test@ORA10G>
test@ORA10G> create table t as
2 select rownum x, rownum*10 y from dual connect by level <= 4;
Table created.
test@ORA10G>
test@ORA10G> --
test@ORA10G> select * from monetary_trans;
HOUSEHOLD_ID RECEIVED_
1 28-DEC-08
1 29-DEC-08
1 30-DEC-08
2 31-DEC-08
2 01-JAN-09
test@ORA10G> select * from t;
X Y
1 10
2 20
3 30
4 40
test@ORA10G>
test@ORA10G> --
test@ORA10G> -- the function code could be rewritten as follows
test@ORA10G> --
test@ORA10G> select household_id,
2 ltrim(sys_connect_by_path(rd,','),',') payment_dates
3 from
4 (
5 select household_id,
6 to_char(received_date,'mm/dd/yy') as rd,
7 row_number() over (partition by household_id order by 1) rn,
8 count(*) over (partition by household_id) cnt
9 from monetary_trans
10 -- and the constraints here in the where clause
11 )
12 where level = cnt
13 start with rn = 1
14 connect by prior household_id = household_id
15 and prior rn = rn - 1
16 and household_id = 1 -- <== this is the input parameter value
17 ;
HOUSEHOLD_ID PAYMENT_DATES
1 12/28/08,12/29/08,12/30/08
test@ORA10G>
test@ORA10G> --
test@ORA10G> -- and can be used as an inline view when joined with other tables
test@ORA10G> --
test@ORA10G> select t.y,
2 fn.payment_dates
3 from t,
4 (select household_id,
5 ltrim(sys_connect_by_path(rd,','),',') payment_dates
6 from (select household_id,
7 to_char(received_date,'mm/dd/yy') as rd,
8 row_number() over (partition by household_id order by 1) rn,
9 count(*) over (partition by household_id) cnt
10 from monetary_trans)
11 where level = cnt
12 start with rn = 1
13 connect by prior household_id = household_id
14 and prior rn = rn - 1
15 ) fn
16 where t.x = fn.household_id
17 ;
Y PAYMENT_DATES
10 12/28/08,12/29/08,12/30/08
20 12/31/08,01/01/09
test@ORA10G>
test@ORA10G>HTH
isotope -
Error in Stoerd Procedure But working in Anonymous Block.
declare
Cursor Cur Is
Select 'Alter '||Object_Type||' '||Object_Name||' Compile' Invalid_Obj, Object_Type, Object_Name
From Dba_Objects A
Where A.Owner='Dataload' And A.Status='Invalid' ;
Begin
For I In Cur
Loop
Begin
Execute Immediate I.Invalid_Obj;
Exception
When Others Then
Null;--Dbms_Output.Put_Line(Sqlerrm||' : '||I.Object_Type||' '||I.Object_Name);
End;
End Loop;
Exception
When Others Then
Null;--Dbms_Output.Put_Line(Sqlerrm);
End;
Above anonymous block Run successfully.
but when I create it as stored procedure then, it give error like
Dba_Objects does not exist.
Please, suggest what I do for stored procedure?
Edited by: Nilesh Hole on Jun 2, 2010 12:00 AMIf you don't have any sys rights you either should
a) ask the DBA to run utlrp (preferred, as that always executes compilation in the right order)
b) do not use dba_objects but user_objects, assuming you are connected as DATALOAD
In a normal situation this shouldn't be necessary, so you should still question why you even want to do this (and are reinventing the wheel). Also the dbms_utility package has a COMPILE_SCHEMA procedure.
Sybrand Bakker
Senior Oracle DBA -
Handling loop exception in an anonymous block
hI ,
I have a an anonymous block
declare
cursor
local variables
begin
open cursor
some statements
loop
some statement ;
some othet statement;
select something from sometablein local variable where some field = cursor.value ;
some more statements
end loop
some more statements
exception
when whatever
then whatever
end;
Now my select statement may give a NO_DATA_FOUND error which i want to catch and ignore .
Pls tell me how to do it.So that mean you can have multiple exception blocks
in a pl/sql script ?You can have one exception handler per execution block.
Execution blocks can be nested inside other execution blocks.
Handling the error within one exception handler causes execution to return out to the execution of the parent block.
Raising an error within one exception handler causes the execution to go straight to the exception handler of the parent block.
e.g.
-- execution block 1
BEGIN
-- execution block 2
DECLARE
myvar number;
BEGIN
SELECT mynumber INTO myvar FROM mytable;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL; -- handle error and return execution to block 1
WHEN OTHERS THEN
RAISE; -- raise any other errors to block 1 exception handler
END; -- block 2
DBMS_OUTPUT.PUT_LINE('Select took place successfully or no data was found');
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred either in block1 or in block 2 (except for NO_DATA_FOUND in block2)');
END; -
Calling a function which has a CLOB parameter via an anonymous block.
OK,
we are moving a lot of exports currently done by Crystal to just be done by stored procs.
So we have a load of existing, some extremely length SQL statements used for these exports.
IN the exports, we have meaningful column headings, so we have a 'lookup' file where all the column names are listed with the desired column name text listed against it.
So - to make our lives easier(i thought) , I have written a Oracle function to extract al;l of the column names as a list (see below).
It works fine except for when I am trying to pass in a SQL treatment that is longer than 4000 character.
What I want to be able to do is simply have an anonymous block that callls my function, I will be running this via SQL explorer.
Something like......
DECLARE
theSQL CLOB;
BEGFIN
theSQL := 'SELECT * FROM ORDERS WHERE 1=0';
SELECT GET_COLUNS_AS_LIST( theSQL, 0 ) FROM DUAL;
END;
However, when I run this I get the error................
PLS-00428: an INTO clause is expected in this SELECT statement
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
If I hard code the SQL like this, SELECT GET_COLUNS_AS_LIST( 'SELECT * FROM ORDERS WHERE 1=0', 0 ) FROM DUAL; all is well.
Also, I am going to need to be able to pass in SQL ststement longer that 4000 characters as weel so please bear that in mind.
I am not an Oracle guy, so I guess I am missing something fundamental - Please enlighten me with regards to this.
Any help extremely appreciated.
CREATE OR REPLACE FUNCTION GET_COLUNS_AS_LIST( P_SQL IN VARCHAR2, Add_Equals_Sign Number := 0)
RETURN CLOB
IS
fResult VARCHAR2(32000);
HNDL NUMBER;
d NUMBER;
colCount INTEGER;
i INTEGER;
rec_tab DBMS_SQL.DESC_TAB;
cCRLF VARCHAR(2) := CHR(13) || CHR(10);
LONG_SQL dbms_sql.varchar2s;
n INTEGER;
l INTEGER;
u INTEGER;
StartPos INTEGER;
BEGIN
--INITIIALISE RESULT
fResult := '';
HNDL := DBMS_SQL.OPEN_CURSOR;
l := Length( P_SQL );
u := ( l / 1000 ) + 1;
FOR n IN 1..u
LOOP
StartPos := ( n - 1 ) + 1;
LONG_SQL( n ) := SubStr( P_SQL, StartPos, 1000 );
END LOOP;
if HNDL <> 0 THEN
DBMS_SQL.PARSE ( c => HNDL,
statement => LONG_SQL,
lb => 1,
ub => u,
lfflg => false,
language_flag => DBMS_SQL.NATIVE );
--DBMS_SQL.PARSE( HNDL, P_SQL, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE( HNDL );
DBMS_SQL.DESCRIBE_COLUMNS( HNDL, colCount, rec_tab);
FOR i in 1..colCount
LOOP
IF Add_Equals_Sign > 0 AND i > 1 THEN
fResult := ltrim( fResult || '=' || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
ELSE
fResult := ltrim( fResult || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
END IF;
END LOOP;
IF Add_Equals_Sign > 0 THEN
fResult := fResult ||'=';
END IF;
ELSE
fResult := '!!COULD NOT OPEN CURSOR!!';
fResult := P_SQL;
END IF;
RETURN fResult;
--Tidy Up
DBMS_SQL.CLOSE_CURSOR(HNDL);
Return 'EGG';
END;
--EXAMPLE USAGE
--Select GET_COLUNS_AS_LIST
--Select * from SALES_TYPE
--', 1) FROM DUAL;So I have ended up with this.
When I next get some time, I'd like to be able to strip out the table and simply output the results to an SQL Developer script window without having to go through the table.
Now this works - but if you see that I am doing something wrong - please point it out.
Many thanks,
Ant
CREATE OR REPLACE FUNCTION GET_COLUNS_AS_LIST( P_SQL IN CLOB, Add_Equals_Sign Number := 0)
RETURN VARCHAR2
IS
fResult VARCHAR2(32000);
HNDL NUMBER;
d NUMBER;
colCount INTEGER;
i INTEGER;
ChunkSize INTEGER;
rec_tab DBMS_SQL.DESC_TAB;
cCRLF VARCHAR(2) := CHR(13) || CHR(10);
LONG_SQL dbms_sql.varchar2s;
n INTEGER;
l INTEGER;
u INTEGER;
StartPos INTEGER;
BEGIN
--INITIIALISE RESULT
HNDL := 0;
ChunkSize := 4;
fResult := '';
--fResult := fResult|| 'A';
HNDL := DBMS_SQL.OPEN_CURSOR;
--l := Length( P_SQL );
l := dbms_lob.getLength( P_SQL );
--l := 50;
u := Round( l / ChunkSize ) + 1;
--fResult := fResult|| 'B';
FOR n IN 1..u
LOOP
StartPos := ( ( n - 1 ) * ChunkSize ) + 1;
IF StartPos = 0 THEN
StartPos := 1;
END IF;
--LONG_SQL( n ) := SubStr( P_SQL, StartPos, ChunkSize );
LONG_SQL( n ) := DBMS_LOB.SUBSTR( P_SQL, ChunkSize, StartPos );
END LOOP;
--fResult := fResult|| 'C';
if HNDL <> 0 THEN
DBMS_SQL.PARSE ( c => HNDL,
statement => LONG_SQL,
lb => 1,
ub => u,
lfflg => false,
language_flag => DBMS_SQL.NATIVE );
--DBMS_SQL.PARSE( HNDL, P_SQL, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE( HNDL );
DBMS_SQL.DESCRIBE_COLUMNS( HNDL, colCount, rec_tab);
--fResult := fResult|| 'D';
FOR i in 1..colCount
LOOP
IF Add_Equals_Sign > 0 AND i > 1 THEN
fResult := ltrim( fResult || '=' || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
ELSE
fResult := ltrim( fResult || cCRLF || UPPER( rec_tab( i ).col_name ), cCRLF );
END IF;
END LOOP;
IF Add_Equals_Sign > 0 THEN
fResult := fResult ||'=';
END IF;
ELSE
fResult := '!!COULD NOT OPEN CURSOR!!';
END IF;
RETURN fResult;
--Tidy Up
IF HNDL <> 0 THEN
DBMS_SQL.CLOSE_CURSOR(HNDL);
END IF;
END;
-- !!!!HOW TO USE THIS FUNCTION!!!!
BEGIN
EXECUTE IMMEDIATE ('DROP TABLE RPT_COLNAME_LOOKUPS;');
COMMIT;
EXECUTE IMMEDIATE ('CREATE TABLE RPT_COLNAME_LOOKUPS( COLUMN_NAME CLOB );');
COMMIT;
EXCEPTION WHEN OTHERS THEN NULL;
END;
DECLARE
theSQL Clob;
myresult CLOB;
BEGIN
--CLEAR OUT PREVIOUS RWS
DELETE FROM RPT_COLNAME_LOOKUPS; COMMIT;
--ASSIGN THE SQL TO RUN IT FOR
theSQL := '
SELECT
EVENT.EVENT_ID AS COCK_SUCKER,
EVENT.EVENT_CODE, BLAH, BLAH, VERY LONG SQL STATEMENT';
--CALL THE FUNCTION PASSING IN THE SQL AND IF I WANT THE = OR NOT
SELECT GET_COLUNS_AS_LIST( theSQL, 1 ) INTO myresult FROM DUAL;
--INSERT THE RESULTS INTO A TABLE SO WE CAN GRAB THEM
INSERT INTO RPT_COLNAME_LOOKUPS SELECT myresult FROM DUAL;
COMMIT;
END;
--THEN LOOK AT THE COLUMNS NAMES IN THIS TABLE
--SELECT * FROM RPT_COLNAME_LOOKUPS;
--############################################################################# -
PL anonymous block does everything, but then gets stuck
We have a PL/SQL block that loops through a cursor, and inserts data into another table. We're having a strange issue with it... Every single line of code within it appears to function correctly... It does everything we want it to. The last line on it calls a simple function that writes a record to a table we made, to indicate it has completed. It does that, and we can see the record is inserted successfully.
The problem: even though we can see it did everything, it gets "stuck". If we run it as a anonymous block, the sql plus session will just stay stuck. Same thing if we turn it into a procedure and invoke it. It just stays stuck. Viewing it from OEM... We can see the session as "active", but it doesn't show that it's currently executing anything.
How can we go about figuring out what the problem is?
We've tried it on four databases... All windows platforms.. Three were oracle 10g, one was Oracle 11g. One more interesting note: one of the 10g ones... the problem does not occur... the script finishes fine. But, we don't know what is different about this database from the others.
We also notice the problem doesn't happen if we limit the amount of records... the initial cursor we process, if we limit it using "rownum < 100" or something like that, it will also always finish fine.
This is the script:
set echo on
set serveroutput on
declare
n_notes_count number;
n_records_read number;
dt_today date;
MYDATE DATE;
dt_comment_date date;
dt_updated_date date;
t_conv_exceptions "ODB"."CONVERSION_EXCEPTIONS" %ROWTYPE;
t_conv_exceptions_default "ODB"."CONVERSION_EXCEPTIONS" %ROWTYPE;
t_note_pad "ODB"."NOTE_PAD"%ROWTYPE;
t_note_pad_clear "ODB"."NOTE_PAD"%ROWTYPE;
t_pfcomm "PMI"."PFCOMM"%ROWTYPE;
c_created_by "ODB"."NOTE_PAD"."CREATED_BY" % type ;
-- Exceptions to be raised
ex_notes_number_blank EXCEPTION;
--ex_category_not_exists EXCEPTION;
--....more to come.....
CURSOR cur_notes IS
SELECT PF."MMNUM",
PF."MMLIN",
PF."MMDES",
PF."MMUSR",
PF."MMMM",
PF."MMDD",
PF."MMYY",
PF."MMCC",
--"pfcomm"."mmchr",
--"pfcomm"."mncmn",
--"pfcomm"."mmtype",
PF."MMUSRU",
PF."MMMMU",
PF."MMDDU",
PF."MMYYU",
PF."MMCCU"
FROM PMI."PFCOMM" PF
WHERE TRIM(PF."MMDES") IS NOT NULL
ORDER BY PF."MMNUM", PF."MMLIN";
BEGIN
-- Initialize variables
dt_today := "ODB"."PKG_APPLICATION_FUNCTION"."CURRENTDATETIME";
c_created_by :='PFCOMM';
-- Setup defaults for exceptions table
t_conv_exceptions_default."SCRIPT" := 'atlas_notes';
t_conv_exceptions_default."EXECUTION_DATE" := dt_Today;
t_conv_exceptions_default."CREATED_BY" := c_created_by;
-- Set up header record for exception
t_conv_exceptions := t_conv_exceptions_default;
t_conv_exceptions.column_01 := 'NOTES';
t_conv_exceptions.header := 'Y';
ODB.PKG_CONVERSIONS_EXCEPTIONS.writeException(t_conv_exceptions, false);
-- Count records in table
SELECT COUNT(*)
INTO n_records_read
FROM PMI."PFCOMM";
-- Delete previously inserted records
DELETE FROM "ODB"."NOTE_PAD" NP
WHERE NP."CREATED_BY" = c_created_by or NP."MODIFIED_BY" = c_created_by;
DELETE FROM "ODB"."NOTE_PAD" NP
WHERE NP."CREATED_BY" = 'PFCOMM2' or NP."MODIFIED_BY" = 'PFCOMM2';
DELETE FROM "ODB"."CONVERSION_EXCEPTIONS" CV
WHERE CV."CREATED_BY" IN (c_created_by,'PFCOMM2');
COMMIT;
/* Do Fetch here */
OPEN cur_notes;
LOOP
FETCH cur_notes
INTO t_pfcomm."MMNUM",
t_pfcomm."MMLIN",
t_pfcomm."MMDES",
t_pfcomm."MMUSR",
t_pfcomm."MMMM",
t_pfcomm."MMDD",
t_pfcomm."MMYY",
t_pfcomm."MMCC",
--"t_pfcommcomm"."mmchr",
--"t_pfcommcomm"."mncmn",
--"t_pfcommcomm"."mmtype",
t_pfcomm."MMUSRU",
t_pfcomm."MMMMU",
t_pfcomm."MMDDU",
t_pfcomm."MMYYU",
t_pfcomm."MMCCU";
EXIT
WHEN cur_notes % NOTFOUND;
-- Clear Variables
t_note_pad := t_note_pad_clear;
dt_comment_date := null;
dt_updated_date := null;
-- Begin variable assignments
t_conv_exceptions."COLUMN_01" := t_note_pad."NOTES";
t_note_pad."NOTES" := t_pfcomm."MMNUM";
t_note_pad."NOTES_TEXT" := t_pfcomm."MMDES";
-- Validate required fields
If t_note_pad."NOTES" is null Then
raise ex_notes_number_blank;
End if;
-- Sequence lines correctly
SELECT NVL( MAX("ODB"."NOTE_PAD"."NOTES_LINE"), 0)
INTO t_note_pad."NOTES_LINE"
FROM "ODB"."NOTE_PAD"
WHERE "ODB"."NOTE_PAD"."NOTES" = t_note_pad."NOTES"
-- Next note line number to insert
If t_note_pad."NOTES_LINE" is null Then
t_note_pad."NOTES_LINE" := 1;
Else
t_note_pad."NOTES_LINE" := t_note_pad."NOTES_LINE" + 1;
End if;
-- MMDDCCYY - Comment Date
If t_pfcomm."MMMM" > 0 Or t_pfcomm."MMDD" > 0 Or t_pfcomm."MMCC" > 0 Or t_pfcomm."MMYY" > 0 Then
SELECT TO_DATE(LPAD(t_pfcomm."MMMM",2,'0') || LPAD(t_pfcomm."MMDD",2,'0') || LPAD(t_pfcomm."MMCC",2,'0')|| LPAD( t_pfcomm."MMYY",2,'0'),'MMDDYYYY') INTO dt_comment_date FROM DUAL;
End if;
-- MMDDCCYY - Updated Date
If t_pfcomm."MMMMU" > 0 Or t_pfcomm."MMDDU" > 0 Or t_pfcomm."MMCCU" > 0 Or t_pfcomm."MMYYU" > 0 Then
SELECT TO_DATE(LPAD(t_pfcomm."MMMMU",2,'0') || LPAD(t_pfcomm."MMDDU",2,'0') || LPAD(t_pfcomm."MMCCU",2,'0')|| LPAD( t_pfcomm."MMYYU",2,'0'),'MMDDYYYY') INTO dt_updated_date FROM DUAL;
End if;
-- Updated user information
IF dt_updated_date is not null Then
t_note_pad."CREATED_BY" := TRIM(t_pfcomm."MMUSRU");
t_note_pad."CREATED_DATE" := dt_updated_date;
Elsif dt_comment_date is not null Then
t_note_pad."CREATED_BY" := TRIM(t_pfcomm."MMUSR");
t_note_pad."CREATED_DATE" := dt_comment_date;
Else
t_note_pad."CREATED_BY" := c_created_by;
t_note_pad."CREATED_DATE" := dt_today;
END IF;
/* Validate mandatory fields of TRAX table */
IF t_note_pad.NOTES = 0 THEN
t_note_pad.NOTES :=null;
End If;
IF t_note_pad.NOTES_LINE is null THEN
t_note_pad.NOTES_LINE := 1;
End If;
IF TRIM(t_note_pad.PRINT_NOTES) is null Then
t_note_pad.PRINT_NOTES := 'YES';
END IF;
IF TRIM(t_note_pad.NOTES_CATEGORY) is null THEN
t_note_pad.NOTES_CATEGORY := 'NORMAL';
END IF;
If TRIM(t_note_pad."CREATED_BY") is null Then
t_note_pad."CREATED_BY" := c_created_by;
End if;
If TRIM(t_note_pad."MODIFIED_BY") is null Then
t_note_pad."MODIFIED_BY" := c_created_by;
End if;
If TRIM(t_note_pad."MODIFIED_DATE") is null Then
t_note_pad."MODIFIED_DATE" := dt_today;
End if;
If TRIM(t_note_pad."CREATED_DATE") is null Then
t_note_pad."CREATED_DATE" := dt_today;
End if;
-- end structure validation
/* Do Insert here here */
insert into "ODB"."NOTE_PAD"
values t_note_pad;
commit;
END LOOP;
dbms_output.put_line('After loop.');
CLOSE cur_notes;
-- Update NOTES Switch
SELECT MAX(NT."NOTES") + 100
INTO n_notes_count
FROM "ODB"."NOTE_PAD" NT
UPDATE "ODB"."SYSTEM_TRAN_CONFIG"
SET "CONFIG_NUMBER" = n_notes_count,
"MODIFIED_BY" = 'TRAXCNV',
"MODIFIED_DATE" = dt_today
WHERE ( ODB."SYSTEM_TRAN_CONFIG"."SYSTEM_TRANSACTION" = 'CONFIGURATION' ) AND
( ODB."SYSTEM_TRAN_CONFIG"."SYSTEM_CODE" ='NOTES' )
COMMIT;
dbms_output.put_line('before audit.');
/* Do Save Audit record */
"ODB"."PKG_CONVERSIONS_EXCEPTIONS".writeAudit(t_conv_exceptions."SCRIPT",c_created_by,n_records_read,dt_today);
dbms_output.put_line('After audit.');
SELECT SYSDATE INTO MYDATE FROM DUAL;
-- Begin exception handling.
exception
when ex_notes_number_blank then
t_conv_exceptions.exception_description := 'Note number is blank.';
ODB.PKG_CONVERSIONS_EXCEPTIONS.writeException(t_conv_exceptions, false);
when others then
t_conv_exceptions.exception_description := substr(SQLERRM,1,1000);
ODB.PKG_CONVERSIONS_EXCEPTIONS.writeException(t_conv_exceptions, false);
RAISE;
-- End exception handling.
dbms_output.put_line('before end.');
END ;
/Avoid row-at-a-time processing if at all possible (cursor for loops, periodic commits, etc).
Try adding some calls to dbms_application_info.set_module (or set_action) in order to find out where your code is. -
Can we declare a Cursor in Package Specs?
Dear buddies
Can I Declare a Cursor in Package Specs so that I can call that cursor and use its data in some procedures and functions of package. Otherwise I've to write that cursor for every sub-program of a package which I don't feel a smart way to accomplish the job.Hi,
here is a short example with the whole way down. Maybe the concept is getting clearer with this:
first of all, if you do not have the table emp, here the DDL for this example.
Be carefull, works only for german clients because of the names of months, sorry for that.
CREATE TABLE EMP
(EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7, 2),
COMM NUMBER(7, 2),
DEPTNO NUMBER(2));
set echo on
INSERT INTO EMP VALUES
(7369, 'SMITH', 'CLERK', 7902,
TO_DATE('17-DEZ-1980', 'DD-MON-YYYY'), 800, NULL, 20);
INSERT INTO EMP VALUES
(7499, 'ALLEN', 'SALESMAN', 7698,
TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600, 300, 30);
INSERT INTO EMP VALUES
(7521, 'WARD', 'SALESMAN', 7698,
TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30);
INSERT INTO EMP VALUES
(7566, 'JONES', 'MANAGER', 7839,
TO_DATE('2-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20);
INSERT INTO EMP VALUES
(7654, 'MARTIN', 'SALESMAN', 7698,
TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30);
INSERT INTO EMP VALUES
(7698, 'BLAKE', 'MANAGER', 7839,
TO_DATE('1-MAI-1981', 'DD-MON-YYYY'), 2850, NULL, 30);
INSERT INTO EMP VALUES
(7782, 'CLARK', 'MANAGER', 7839,
TO_DATE('9-JUN-1981', 'DD-MON-YYYY'), 2450, NULL, 10);
INSERT INTO EMP VALUES
(7788, 'SCOTT', 'ANALYST', 7566,
TO_DATE('09-DEZ-1982', 'DD-MON-YYYY'), 3000, NULL, 20);
INSERT INTO EMP VALUES
(7839, 'KING', 'PRESIDENT', NULL,
TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10);
INSERT INTO EMP VALUES
(7844, 'TURNER', 'SALESMAN', 7698,
TO_DATE('8-SEP-1981', 'DD-MON-YYYY'), 1500, 0, 30);
INSERT INTO EMP VALUES
(7876, 'ADAMS', 'CLERK', 7788,
TO_DATE('12-JAN-1983', 'DD-MON-YYYY'), 1100, NULL, 20);
INSERT INTO EMP VALUES
(7900, 'JAMES', 'CLERK', 7698,
TO_DATE('3-DEZ-1981', 'DD-MON-YYYY'), 950, NULL, 30);
INSERT INTO EMP VALUES
(7902, 'FORD', 'ANALYST', 7566,
TO_DATE('3-DEZ-1981', 'DD-MON-YYYY'), 3000, NULL, 20);
INSERT INTO EMP VALUES
(7934, 'MILLER', 'CLERK', 7782,
TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10);2. Package Spec:
create or replace
package test_cursor as
--Type for the returncode of the function
TYPE typ_emp IS TABLE OF emp%rowtype;
--Array for fetching, of course also possible in the body
t_emp typ_emp;
--function wich returns the array from fetching the cursor
function get_emp return typ_emp;
--function for manupilation data retrieved by the function
PROCEDURE man_emp;
end test_cursor;3. Package Body
create or replace
package body test_cursor as
FUNCTION get_emp RETURN typ_emp AS
cursor c_emp is select * from emp;
BEGIN
open c_emp;
fetch c_emp BULK COLLECT INTO t_emp;
CLOSE c_emp;
--t_emp returns the whole table set from emp
return t_emp;
end get_emp;
PROCEDURE man_emp AS
--just for not confusing names, is the same as t_emp of course
v_emp_array typ_emp;
BEGIN
--call the function and retrieve the whole data set
v_emp_array := get_emp;
--now manipulate the data, in this case just write the names to the calling client
FOR rec IN v_emp_array.FIRST .. v_emp_array.LAST
loop
dbms_output.put_line(v_emp_array(rec).ename);
end loop;
end man_emp;
end test_cursor;4. Calling the procedure
SET serveroutput ON
exec test_cursor.man_emp;5. And this is the result:
anonymer Block abgeschlossen
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLERPlease be aware, this is just for demonstration purpose, of course it makes no sense to display the names this way. But how to call a funktion returning arrays with datasets from fetching cursors is shown here.
Hth
Joerg -
Anonymous Block with Variable and SELECT
Hi Guys,
I am struggling to connect the material I am learning. I read about anonymous blocks and variables so I want to write a
nice and neat select with all the fancy stuff (variables, exceptions) to get it right and to it as I read in the book.
DECLARE
MYSTRING VARCHAR(10);
MYSTIRNG := 'X';
BEGIN
SELECT * FROM DUAL WHERE DUMMY = MYSTRING
END;
but....this causes one error after the other. Am I getting the concept wrong here or is it a syntax error?cant I just get the result without using variable to store the result in the first place???Perhaps you're better off using a REF CURSOR (a.k.a. cursor variable).
That way you'll pass a resultset to the caller and you don't need any variables to select into.
You can read about them here:
http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php
Re: PL/SQL 101 : Understanding Ref Cursors
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10766/tdddg_subprograms.htm#TDDDG99939 -
Hi,
if run the below anonymous Block,it shows ouput as NULL,
I want to display the column names from the cursor.
DECLARE
V_PK_COLS VARCHAR2(400);
P_COLUMN_NAME VARCHAR2(400) := 'CF_FEEDBACK_KEY,CF_CUSTOMER_KEY';
P_TABLE_NAME VARCHAR2(400) := 'T_ID_CMS_FEEDBACK_DETAILS';
CURSOR C_PK_COLS IS
SELECT UCC.COLUMN_NAME
FROM USER_CONS_COLUMNS UCC,USER_CONSTRAINTS UC
WHERE UCC.TABLE_NAME = P_TABLE_NAME
AND UC.CONSTRAINT_TYPE = 'P'
AND UCC.CONSTRAINT_NAME = UC.CONSTRAINT_NAME
AND UC.TABLE_NAME=UCC.TABLE_NAME
AND UCC.COLUMN_NAME IN (CHR(39)||REPLACE(P_COLUMN_NAME,',',''',''')||CHR(39))
--AND UCC.COLUMN_NAME IN(P_COLUMN_NAME)
ORDER BY UCC.POSITION;
BEGIN
OPEN C_PK_COLS;
FETCH C_PK_COLS INTO V_PK_COLS;
CLOSE C_PK_COLS;
DBMS_OUTPUT.PUT_LINE('OutPut :- ' || P_COLUMN_NAME);
END;
Regards,
FameWhy not use a loop, in case the key consists of more than one column:
Try something like:
DECLARE
V_PK_COLS VARCHAR2(400);
P_COLUMN_NAME VARCHAR2(400) := 'CF_FEEDBACK_KEY,CF_CUSTOMER_KEY';
P_TABLE_NAME VARCHAR2(400) := 'T_ID_CMS_FEEDBACK_DETAILS';
BEGIN
for rec in ( SELECT UCC.COLUMN_NAME
FROM USER_CONS_COLUMNS UCC, USER_CONSTRAINTS UC
WHERE UCC.TABLE_NAME = P_TABLE_NAME
AND UC.CONSTRAINT_TYPE = 'P'
AND UCC.CONSTRAINT_NAME = UC.CONSTRAINT_NAME
AND UC.TABLE_NAME = UCC.TABLE_NAME
AND UCC.COLUMN_NAME IN
(CHR(39) || REPLACE(P_COLUMN_NAME, ',', ''',''') || CHR(39))
--AND UCC.COLUMN_NAME IN(P_COLUMN_NAME)
ORDER BY UCC.POSITION )
loop
DBMS_OUTPUT.PUT_LINE('OutPut :- ' || rec.COLUMN_NAME);
end loop;
END; -
Cursor Variable in Nested Block
Dear all,
I have a package that has procedures that open cursor variables and print the queries of sample schema HR. There's one procedure that opens the cursor with an input integer to choose which query that wants to be fetched. The other prints the query by fetching the cursor in a nested block with exceptions. The following package runs as intended, it prints all the three options without any problems:
CREATE OR REPLACE PACKAGE admin_data AS
TYPE gencurtyp IS REF CURSOR;
PROCEDURE open_cv (generic_cv IN OUT gencurtyp, choice INT);
procedure print_cv (generic_cv gencurtyp);
END admin_data;
CREATE OR REPLACE PACKAGE BODY admin_data AS
PROCEDURE open_cv (generic_cv IN OUT gencurtyp, choice INT) IS
BEGIN
IF choice = 1 THEN
OPEN generic_cv FOR SELECT * FROM jobs where job_id='ST_MAN';
ELSIF choice = 2 THEN
OPEN generic_cv FOR SELECT * FROM departments where department_id=270;
ELSIF choice = 3 THEN
OPEN generic_cv FOR SELECT * FROM employees where employee_id=206;
END IF;
END;
procedure print_cv (generic_cv gencurtyp)is
employees_rec employees%rowtype;
departments_rec departments%rowtype;
jobs_rec jobs%rowtype;
begin
fetch generic_cv into jobs_rec;
dbms_output.put_line(jobs_rec.job_title);
exception
when ROWTYPE_MISMATCH then
begin
fetch generic_cv into departments_rec;
dbms_output.put_line(departments_rec.department_name);
exception
when ROWTYPE_MISMATCH then
dbms_output.put_line('row mismatch');
fetch generic_cv into employees_rec;
dbms_output.put_line(employees_rec.first_name);
when OTHERS then
dbms_output.put_line('others');
fetch generic_cv into employees_rec;
dbms_output.put_line(employees_rec.first_name);
end;
end print_cv;
END admin_data;
declare
some_cur admin_data.gencurtyp;
begin
admin_data.open_cv(some_cur,1);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,2);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,3);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,3);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,1);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,2);
admin_data.print_cv(some_cur);
end;
17 /
Stock Manager
Payroll
row mismatch
William
row mismatch
William
Stock Manager
Payroll
PL/SQL procedure successfully completed.The innermost block executes 'rowtype mismatch' exception block, which fetches
SELECT * FROM employees where employee_id=206 query.
This time, I switch the query fetch so that
SELECT * FROM employees where employee_id=206query is in the outermost block and
SELECT * FROM jobs where job_id='ST_MAN' is in the innermost block. The package body looks like this:
CREATE OR REPLACE PACKAGE BODY admin_data AS
PROCEDURE open_cv (generic_cv IN OUT gencurtyp, choice INT) IS
BEGIN
IF choice = 1 THEN
OPEN generic_cv FOR SELECT * FROM jobs where job_id='ST_MAN';
ELSIF choice = 2 THEN
OPEN generic_cv FOR SELECT * FROM departments where department_id=270;
ELSIF choice = 3 THEN
OPEN generic_cv FOR SELECT * FROM employees where employee_id=206;
END IF;
END;
procedure print_cv (generic_cv gencurtyp)is
employees_rec employees%rowtype;
departments_rec departments%rowtype;
jobs_rec jobs%rowtype;
begin
fetch generic_cv into employees_rec;
dbms_output.put_line(employees_rec.first_name);
exception
when ROWTYPE_MISMATCH then
begin
fetch generic_cv into departments_rec;
dbms_output.put_line(departments_rec.department_name);
exception
when ROWTYPE_MISMATCH then
dbms_output.put_line('row mismatch');
fetch generic_cv into jobs_rec;
dbms_output.put_line(jobs_rec.job_title);
when OTHERS then
dbms_output.put_line('others');
fetch generic_cv into jobs_rec;
dbms_output.put_line(jobs_rec.job_title);
end;
end print_cv;
END admin_data;
then I run the same anonymous block, I get:declare
some_cur admin_data.gencurtyp;
begin
admin_data.open_cv(some_cur,1);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,2);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,3);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,3);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,1);
admin_data.print_cv(some_cur);
admin_data.open_cv(some_cur,2);
admin_data.print_cv(some_cur);
end;
17 /
others
Payroll
William
William
others
Payroll
PL/SQL procedure successfully completed.
The strangest thing is the innermost block execute OTHERS exception block instead of ROWTYPE MISMATCH and the the record doesn't fetch anything. What happen? How come the result is different when I only switch the query?
Best regards,
ValHi Sy,
thanks for the reply, yes I agree that the code is cumbersome, I'm studying to prepare OCP PL/SQL certification, so I'm playing around with cursor variable in order to grasp the whole concept. I'm observing the behaviour of weak cursor variable when getting passed into a function and fetched couple of times and exploring exception propagation in the same time. This why the code looks not relevant in the real world.
Anyway, I just curious how it behaves like that. Here's my instance info:
SQL> select * from v$version
2 ;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for Linux: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production -
Function defined in anonymous block?
Quick question. I'd like to define a temporary function in a PL/SQL anonymous block. I'm thinking that I've seen an example of that done before, but I can't seem to find the example. Here's the source. Given a table name, I want to return a comma-delimited list of the columns in the table. As a stored function, this works like a charm:
CREATE OR REPLACE
FUNCTION columnlist_csv (in_tablename VARCHAR2) RETURN VARCHAR2 IS
v_columnlist VARCHAR2(4000);
v_num_columns NUMBER(4,0);
CURSOR c1(c1_tablename VARCHAR2) IS
SELECT column_name, column_id FROM user_tab_columns
WHERE table_name = c1_tablename ORDER BY column_id;
BEGIN
SELECT count(*) INTO v_num_columns FROM user_tab_columns WHERE table_name=in_tablename;
FOR c1row IN c1(in_tablename) LOOP
v_columnlist := v_columnlist||c1row.column_name;
IF c1row.column_id < v_num_columns THEN
v_columnlist := v_columnlist||', ';
END IF;
END LOOP;
RETURN v_columnlist;
END;
SELECT columnlist_csv(upper('&tablename')) FROM dual;
But, rather than having the function be a stored function, I'd prefer to define a temporary function on the fly in the script, like below. However, this doesn't work as an anonymous block. I believe I simply have the syntax wrong, and I'm hoping someone like lend a second pair of eyes...
DECLARE
FUNCTION columnlist_csv (in_tablename VARCHAR2) RETURN VARCHAR2 IS
v_columnlist VARCHAR2(4000);
v_num_columns NUMBER(4,0);
CURSOR c1(c1_tablename VARCHAR2) IS
SELECT column_name, column_id FROM user_tab_columns
WHERE table_name = c1_tablename ORDER BY column_id;
BEGIN
SELECT count(*) INTO v_num_columns FROM user_tab_columns WHERE table_name=in_tablename;
FOR c1row IN c1(in_tablename) LOOP
v_columnlist := v_columnlist||c1row.column_name;
IF c1row.column_id < v_num_columns THEN
v_columnlist := v_columnlist||', ';
END IF;
END LOOP;
RETURN v_columnlist;
END;
SELECT columnlist_csv(upper('&tablename')) FROM dual;
Can anyone advise?
Regards,
DaveI want to return a comma-delimited list of the columns in the tableIf this is the goal, you could use a simple SELECT statement, SQL> desc test111;
Name Null? Type
TRX_NUMBER VARCHAR2(20)
TRX_AMOUNT NUMBER(12,2)
SQL> select decode(column_id,1,'',',') || lower(column_name) col_name
2 from user_tab_columns
3 where table_name = upper('&table_name')
4 order by column_id
5 /
Enter value for table_name: test111
old 3: where table_name = upper('&table_name')
new 3: where table_name = upper('test111')
COL_NAME
trx_number
,trx_amountThx,
SriDHAR
Maybe you are looking for
-
Problem in Installation of Oracle Universal Content Management
Hello friends I am Nilesh ,trying to install Oracle UCM on Windows Server 2003. For this I used MS SQL Server 2005 as Database & IIS as Web server. This is giving Error of Connection of UCM & Database. Can you please guide me in installing UCM ?. I a
-
Hi all I want a sample procedure in which i would to like to fetch data and save the output to a XML File. Someone please help me in giving me the sample procedure. Regds Nirmal
-
Check authorization after selection in navigation bar
Hi, there is a standard entry in the navigation bar "Create service ticket" that calls the view set SrvTViewSet for creation of service tickets. The viewset contains of four standard view areas, SrvtHead, SrvtBus, SrvtPartner, SrvtSLA. We have not mo
-
How can i install and activate my Creative suite 2 Standard on my new computer??
My old computer was to slow after many years. Before I dumped it I removed the whole Creative Suite from the computor. Now it is inpossible to activate the program via internet or by telefone. trying to activate I get the message: "Activation Server
-
Missing sorting for Webi Report
In Business Objects XIR2+SP3 with fix pac 3.6, when Applying Drill or when creating a new column the webi loss sort. Please assits