Anonymous Block -- Procedure
How do I make this anonymous block into a procedure?
DECLARE
TYPE actnlog_rt IS RECORD
id actionlog_temp.id%TYPE,
seg action_log_temp.seg%TYPE,
dma action_log_temp.dma%TYPE,
state action_log_temp.state%TYPE
TYPE actnlog_nt IS TABLE OF actnlog_rt INDEX BY pls_integer;
actnlog actnlog_nt;
BEGIN
SELECT DISTINCT nvl(id, ip_address), seg, dma, state
bulk collect
INTO actnlog
FROM action_log_temp
minus
SELECT v_name, seg_string, dma, state
FROM v_map;
FORALL i IN 1 .. actnlog.COUNT
INSERT INTO
(SELECT v_name, seg_string, dma, state FROM v_map)
VALUES actnlog(i);
DBMS_OUTPUT.PUT_LINE(to_char(SQL % rowcount) || ' rows inserted.');
END;
Message was edited by:
vi2167
I see. How would you convert this SQL SELECT and INSERT into PL/SQL?
I could apply the BULK COLLECT...FORALL...model that was used earlier, but not sure about declaring TYPEs. I should declare a new %TYPE for each table.column, right? And should I declare more than one nested table (e.g. actnlog_nt)?
Thank you.
CREATE OR REPLACE VIEW vw_v AS
SELECT x.id,
x.site,
x.adate,
x.imps,
x.cks
FROM
(SELECT v._id,
s.imps,
s.ccks,
s.dma,
s.state,
s.seg,
s.site,
s.adate
FROM
(SELECT nvl(id, ip) AS
name,
dma,
state,
seg,
site,
adate,
SUM(imps) AS
imps,
SUM(cks) AS
cks
FROM actn_log_temp
GROUP BY nvl(id,ip),
dma,
state,
seg,
site,
adate)
s,
v_map v
WHERE v.v_name = s.name
AND v.seg_string = s.seg
AND v.dma = s.dma
AND v.state = s.state)
x;
INSERT
INTO v_d_detail(id, site_path, del_date, imps, cks)
SELECT id,
site,
adate,
imps,
ccks
FROM vw_v;
Message was edited by:
vi2167
Message was edited by:
vi2167
Similar Messages
-
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. -
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 -
Can select resource content in anonymous block, but not in stored procedure
I know the problem relates to the ACLs but am curious about the following behaviour:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
PL/SQL Release 10.2.0.1.0 - Production
CORE 10.2.0.1.0 Production
TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production
running on Windows XP sp2
Trying to access an existing resource '/home/test/test.dtd'
/home is owned by SYS
/home/test is owned by me
/home/test.test.dtd is owned by me
The following SQL and anonymous block retrieve the content of the resource:
select extract(p.res,'/*').getClobVal()
from resource_view p
where p.any_path = '/home/test/test.dtd'
declare
alldata clob;
begin
select extract(p.res,'/*').getClobVal()
into alldata
from resource_view p
where p.any_path = '/home/test/test.dtd'
dbms_output.put_line(substr(alldata, 1, 255));
end;
BUT when I encapsulate the anonymous block in a stored procedure, I am told that the folder '/home/test/' does not exist.
As said, the problem related to the ACL on the folders, what I cannot understand, and caused me considerable confusion, is why I was unable to get the content from a stored procedure when I was able to do so from an anonymous block.
regards
RichardUse equals_path(res,'/home/test/test.dtd') = 1OK, OK, but how do you use wildcards (if you want to) since any_path like '/home/test%' works?
Who was the stored procedure owned by. Was it a stand-alone stored procedure or a
method on a package. If it was a method on a package is it AUTHID creator or AUTHID
definer.Everything apart from the '/home' folder is owned by the current user.
The PL/SQL was in a packaged procedure, a stand-alone stored procedure, and an anonymous block. It exhibited the same behaviour in each. All were defined with default AUTHID which is definers rights which is the same as the current user in this case. -
Reference value of an SQLPLUS variable in a PL/SQL anonymous block
All,
Is there a way of referencing an SQLPLUS variable within a PL/SQL anonymous block. See my example below........
sqlplus -s /@${L_DB_SID} <<-ENDOFSQL >> ${L_LOGFILE}
SET FEEDBACK OFF
SET PAGES 0
SET SERVEROUTPUT ON
WHENEVER SQLERROR EXIT SQL.SQLCODE
WHENEVER OSERROR EXIT 2
VARIABLE l_ret_sts NUMBER;
VARIABLE l_ret_msg VARCHAR2(300);
exec sh_plsql_owner.sh\$secure_batch.p\$set_role(p_ret_sts => :l_ret_sts);
begin
if :l_ret_sts > 0 then
dbms_output.put_line('l_ret_sts:'||:l_ret_sts||':SECURITY');
else
${L_PLSQL_PROG}(p_ret_type => 0, p_ret_sts => :l_ret_sts, p_ret_msg => :l_ret_msg);
dbms_output.put_line('l_ret_sts:'||NVL(:l_ret_sts,0));
dbms_output.put_line('l_ret_msg:'||:l_ret_msg);
end if;
end;
exit
ENDOFSQL
I need to be able to reference :l_ret_sts in the begin block using the if statement "if :l_ret_sts > 0 then"
:l_ret_sts is populated in a procedure call beforehand.
However it seems as though the begin block cannot reference the value returned to :l_ret_sts.
Any ideas.
Ian.Managed to solve this. I put my call to the package that the role enables via dynamic sql....
sqlplus -s /@${L_DB_SID} <<-ENDOFSQL >> ${L_LOGFILE}
SET FEEDBACK OFF
SET PAGES 0
SET SERVEROUTPUT ON
WHENEVER SQLERROR EXIT SQL.SQLCODE
WHENEVER OSERROR EXIT 2
VARIABLE l_ret_sts NUMBER;
VARIABLE l_ret_msg VARCHAR2(300);
exec dbms_application_info.set_client_info('CONTROL-M');
exec sh_plsql_owner.sh\$secure_batch.p\$set_role(p_ret_sts => :l_ret_sts);
declare
v_text varchar2(500);
begin
if :l_ret_sts > 0 then
dbms_output.put_line('l_ret_sts:'||:l_ret_sts||':SECURITY');
else
v_text := 'begin ${L_PLSQL_PROG}(p_ret_type => 0, p_ret_sts => :1, p_ret_msg => :2);end;';
execute immediate v_text using in out :l_ret_sts, in out :l_ret_msg;
dbms_output.put_line('l_ret_sts:'||NVL(:l_ret_sts,0));
dbms_output.put_line('l_ret_msg:'||:l_ret_msg);
end if;
end;
exit
ENDOFSQL
Cheers
Ian. -
Getting value with an anonymous block using ODP
Hi all!
I have a problem I hope someone can help me with. I believe it to be a minor one. I am trying to imbed an anonymous block into my .net app and use it dynamically to get a value from the database depending on the values in a tables. Since my procedure is quite large I am displaying a small example proc for simplicity purposes. Basically I want to execute an anonymous block from my app that will return a value (not a row or rows) from the database. The code is below:
Private Sub test()
Dim cn As New OracleConnection(profileString)
Try
Dim sb As New System.Text.StringBuilder
sb.Append("Declare ")
sb.Append("v_maxnum varchar2(6); ")
sb.Append("Begin ")
sb.Append("Select max(to_number(email_address_id)) into ")
sb.Append("v_maxnum from CVWH14_CDRV_TEST.EMAIL_ADDRESS_TBL; ")
sb.Append("dbms_output.put_line(v_maxnum); ")
sb.Append("Exception ")
sb.Append("When Others ")
sb.Append("Then ")
sb.Append("dbms_output.put_line('Program run errors have occurred.'); ")
sb.Append("End; ")
Dim cmd As New OracleCommand(sb.ToString, cn)
With cmd
cmd.CommandType = CommandType.Text
Dim parm As New OracleParameter
parm.ParameterName = "v_maxnum"
parm.OracleType = OracleType.VarChar
parm.Direction = ParameterDirection.Output
parm.Size = 6
cmd.Connection.Open()
Dim ret As Object = cmd.ExecuteScalar()
Dim res As String = cmd.Parameters.Item(0).Value.ToString -- **Error is occuring here**
cmd.Connection.Close()
cmd.Dispose()
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
'End If
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
The exception error reads "Invalid Index 0 for this OracleParameterCollection with Count=0."
If I can figure out how to get a parameter value from the database via the anonymous block, I can apply the logic to the real application. Any help or direction I could receive would be greatly appreciated. Thanks for reading this post!Thank you for responding. The code that I posted was just one of many ways I have tried. I retried the proc making just 2 changes:
Private Sub test()
Dim cn As New OracleConnection(profileString)
Try
Dim sb As New System.Text.StringBuilder
sb.Append("Declare ")
sb.Append("v_maxnum varchar2(6); ")
sb.Append("Begin ")
sb.Append("Select max(to_number(email_address_id)) into ")
sb.Append("v_maxnum from CVWH14_CDRV_TEST.EMAIL_ADDRESS_TBL; ")
sb.Append("dbms_output.put_line(:v_maxnum); ") -- !Changed this to a bind variable!
sb.Append("Exception ")
sb.Append("When Others ")
sb.Append("Then ")
sb.Append("dbms_output.put_line('Program run errors have occurred.'); ")
sb.Append("End; ")
Dim cmd As New OracleCommand(sb.ToString, cn)
With cmd
cmd.CommandType = CommandType.Text
Dim parm As New OracleParameter
parm.ParameterName = ":v_maxnum" -- !Changed this to a bind variable!
parm.OracleType = OracleType.VarChar
parm.Direction = ParameterDirection.Output
parm.Size = 6
cmd.Connection.Open()
Dim ret As Object = cmd.ExecuteScalar() -- !The error is now occuring here!
Dim res As String = cmd.Parameters.Item(0).Value.ToString
cmd.Connection.Close()
cmd.Dispose()
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
I am now getting the error message "Not all variables bound". Any more help or direction that you could throw my way would be greatly appreciated. -
Performance problem due to anonymous blocks
Hi,
One of the users on our database has created a procedure consisting of many blocks like the one given below:
begin
select func1(var1,var2,var3)into vcompvalue from dual;
if vcompvalue < 0 then
vcompvalue := 0;
end if;
exception when no_data_found then
vcompvalue := 0;
end;
The procedure takes a long time to execute.Instead of writing a block, will writing SQL%NOTFOUND instead of the exception and merging the blocks with rest of the code improve performance?
Thanks for the help!
Vinayak ThatteI would guess it might; you'd be cutting down the number of PL/SQL clauses that have to be parsed, etc, so if you have enough anonymous blocks you may see a difference.
On a more specific note can I just ask why you're checking for NO_DATA_FOUND? If DUAL ever throws this exception you've got serious problems with your database. If it's being thrown by your FUNC1 you might be better off (from a performance point of view) handling that exception within the function.
rgds, APC -
Printing the Package output from Anonymous block
Hi,
I need to call the below package from anonymous block and get the output.
Could you let me know.
I tried using this, but i don't get data.
===========Anonymous Block=====================================================================
declare
var xxdc.xxdc_sr_log_his_pkg.sr_tbl_type;
l_sr_idx_bi BINARY_INTEGER := 0;
BEGIN
xxdc.xxdc_sr_log_his_pkg.service_record('14040',var);
dbms_output.put_line('CLAIM_CREDIT_OFFERS :'||var(l_sr_idx_bi).qa_credit_offers(l_sr_idx_bi).character1 );
end;
=============================================================================================
============================================================================================
Package Spec
TYPE cr_offer_type IS TABLE OF apps.qa_results_v%ROWTYPE
INDEX BY BINARY_INTEGER;
TYPE sr_rec_type IS RECORD
(task_status apps.jtf_task_statuses_tl.name%TYPE
,task_type apps.jtf_task_types_tl.name%TYPE
,qa_credit_offers cr_offer_type
TYPE sr_tbl_type IS TABLE OF sr_rec_type
INDEX BY BINARY_INTEGER;
PROCEDURE service_record(p_service_req_num IN VARCHAR2
,p_service_req_tbl OUT sr_tbl_type
Package Body
FOR emp_row_rec IN cur_credit_off
LOOP
l_sr_tbl(l_sr_idx_bi).qa_credit_offers(l_sr_idx_bi).character1 := emp_row_rec.character1;
--dbms_output.put_line( l_sr_tbl(l_sr_idx_bi).qa_credit_offers(l_sr_idx_bi).character1); --commenting for testing
l_sr_idx_bi := l_sr_idx_bi + 1;
END LOOP;
p_service_req_tbl := l_sr_tbl;
=============================================================================================
ThankHi,
Did you issue the SQL*Plus command
SET SERVEROUTPUT ON
or, if you're using some other front end, its equivalent?
Can you ever see output from dbms_output? For example, what happens when you run this?
SET SERVEROUTPUT ON
BEGIN
dbms_output.put_line ('Hello, world!');
END;
Since I don't have your tables, I can't actually run your code. If you'd post CREATE TABLE and INSERT statements, or re-write the package to reference commonly available tables, such as those in the scott schema, then I could test it. -
Autonomous Transactions usage in PL/SQL anonymous block coding
Hi,
I am trying to incorporate Autonomous Transaction for our work. I am using the tables provided below,
CREATE TABLE T1
F1 INTEGER,
F2 INTEGER
CREATE TABLE T2
F1 INTEGER,
F2 INTEGER
insert into t1(f1, f2)
values(20, 0)
insert into t2(f1, f2)
values(10, 0)
Now, when I use the code snippet given below, it is working as expected.
create or replace procedure p1 as
PRAGMA AUTONOMOUS_TRANSACTION;
begin
update t2
set f2 = 25
where f1 = 10;
commit;
end;
declare
PRAGMA AUTONOMOUS_TRANSACTION;
a integer;
begin
update t1
set f2 = 15
where f1 = 20;
p1();
rollback;
end;
Here, updation in t2 table is commited and t1 is rolled back, it is working as
expected. I would like to achieve the same functionality through PL/SQL
anonymous block coding, to do this, I use the following code snippet,
declare
PRAGMA AUTONOMOUS_TRANSACTION;
a integer;
begin
update t1
set f2 = 15
where f1 = 20;
begin
update t2
set f2 = 35
where f1 = 10;
commit;
end;
rollback;
end;
Here, data in both the tables are commited, how do I change it to work as I
mentioned above like committing t2 alone, please help, thank you.
Regards,
DevaCan you explain what you're trying to accomplish from a business perspective? This doesn't look like a particularly appropriate way to use autonomous transactions, so you may be causing yourself problems down the line.
That said, padders's solution does appear to work for me
SCOTT @ nx102 Local> CREATE TABLE T1
2 (
3 F1 INTEGER,
4 F2 INTEGER
5 )
6 /
Table created.
Elapsed: 00:00:01.03
SCOTT @ nx102 Local>
SCOTT @ nx102 Local>
SCOTT @ nx102 Local> CREATE TABLE T2
2 (
3 F1 INTEGER,
4 F2 INTEGER
5 )
6 /
Table created.
Elapsed: 00:00:00.00
SCOTT @ nx102 Local>
SCOTT @ nx102 Local> insert into t1(f1, f2)
2 values(20, 0)
3 /
1 row created.
Elapsed: 00:00:00.01
SCOTT @ nx102 Local>
SCOTT @ nx102 Local> insert into t2(f1, f2)
2 values(10, 0)
3 /
1 row created.
Elapsed: 00:00:00.01
SCOTT @ nx102 Local> commit;
Commit complete.
Elapsed: 00:00:00.01
SCOTT @ nx102 Local> DECLARE
2 a INTEGER;
3
4 PROCEDURE update_t2
5 IS
6 PRAGMA AUTONOMOUS_TRANSACTION;
7 BEGIN
8 UPDATE t2
9 SET f2 = 35
10 WHERE f1 = 10;
11
12 COMMIT;
13 END update_t2;
14 BEGIN
15 UPDATE t1
16 SET f2 = 15
17 WHERE f1 = 20;
18
19 update_t2;
20
21 ROLLBACK;
22 END;
23 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.04Have you done something else that would cause a deadlock?
Justin -
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. -
Anonymous Block in SQL Developer
I am using SQL Developer 3.1x and trying to run a pretty simple Anonymous block and am having trouble declaring a variable. This block runs successfully:
set SERVEROUTPUT on
--declare
-- V_CRT := CHR(13);
begin
for t in (select owner, table_name from dba_tables where owner = 'ABC123)
LOOP
DBMS_STATS.GATHER_TABLE_STATS(t.owner, t.table_name);
end loop;
DBMS_OUTPUT.PUT_LINE('Statistics Calculations complete');
DBMS_OUTPUT.PUT_LINE('Begin Record Counts');
-- DBMS_OUTPUT.PUT_LINE(v_crt);
-- DBMS_OUTPUT.PUT_LINE(V_CRT);
end;
If I remove my comments in an effort to include my Declare statement, I receive: PLS-00103: Encountered the symbol "=" when expecting one of the following
How do I declare / initialize the variable "v_crt"? Admittedly this is a VERY basic Block but I just started to build out a more "robust" procedure and am getting stumped.
Thank you for your help!The symbol *:=* is for assignment, not variable declaration. Just give the variable name and then its type, like this:DECLARE
V_CRT VARCHAR2(13);You can give it a default value if you want to.DECLARE
V_CRT VARCHAR2(13) := 'Hello';Looks like you want it to be a carriage return character.DECLARE
V_CRT VARCHAR2(1) := CHR(13); -
The output is always "anonymous block completed"
Hi ,
I have written a simple Stored Procedure as shown :
create or replace procedure display
ename out emp.ename%type
is
begin
select ename into ename from emp where empno='7369';
end;
I tried to execute the above using this block
declare
ename emp.ename%type;
begin
display(ename);
dbms_output.put_line(ename);
end;
I am always getting the Output as "anonymous block completed" and nothing else .
Please help . Thanks .Hi:
First type this to enable the output.
SET SERVEROUTPUT ON;Saad, -
Help!! how to call pl/sql anonymous block from java?
I know that jdbc can call a pl/sql package or procedure,but if i
want to call a pl/sql anonymous block, how can i do it? no procedure
name or package name will be offered.
Can u give me a sample code? thanks very muchthanks ,but do u make sure that it can work? i have tried to do like this ,but i can not get it. Or please give me a detail code, thanks very much
-
Basic anonymous block which drops and creates a table
Version: 11.2.0.3
I am fairly new to PL/SQL.
We have a table named CHK_CNFG_DTL.
I want to create a backup table for CHK_CNFG_DTL which will be named like CHK_CNFG_DTL_BKP_<timestamp> eg: CHK_CNFG_DTL_BKP_JULY_22_2013
Creation of this backup table has to be automated so, I want to create an anonymous block which will first drop the existing backup table and then create a new backup table from the original table.
The below code works fine. But the very first time when you run it , the loop won't iterate because there is no such table named CHK_CNFG_DTL_BKP%.
declare
v_stmt varchar2(1000);
v_date date;
begin
for rec in
(select * from user_tables where table_name like 'CHK_CNFG_DTL_BKP%' )
loop
begin
execute immediate 'alter session set nls_date_format=''DD_MON_YYYY''';
v_stmt := 'drop table '||rec.table_name|| ' purge';
dbms_output.put_line(v_stmt); ----- Drops Old backup table
execute immediate v_stmt;
select sysdate into v_date from dual;
v_stmt := 'create table CHK_CNFG_DTL_BKP_'||to_date(v_date)||' as select * from CHK_CNFG_DTL';
dbms_output.put_line('Creating Bkp table CHK_CNFG_DTL_BKP_'|| to_date(v_date) );
dbms_output.put_line(v_stmt);
execute immediate v_stmt; --- Creates new Backup table
exception
when others
then
dbms_output.PUT_LINE (rec.table_name||'-'||sqlerrm);
end;
end loop;
end;
PL/SQL procedure successfully completed.
-- Backup table not created.
SQL> select table_name from user_Tables where table_name like 'CHK_CNFG_DTL%';
TABLE_NAME
CHK_CNFG_DTL
Of course, this can fixed by creating a table like bleow before executing the anonymous block
SQL> create table CHK_CNFG_DTL_BKP_JULY_22_2013 (x varchar2(37));
Table created.
and now the block will succesfully run like
24 end;
25 /
drop table CHK_CNFG_DTL_BKP_JULY_22_2013 purge
Creating Bkp table CHK_CNFG_DTL_BKP_22_JUL_2013
create table CHK_CNFG_DTL_BKP_22_JUL_2013 as select * from CHK_CNFG_DTL
PL/SQL procedure successfully completed.
But this is going to production . We can't a table like CHK_CNFG_DTL_BKP_JULY_22_2013 without a proper business reason.
How can I modify the above code so that if even if there is no such table like 'CHK_CNFG_DTL_BKP%' , it will proceed to create the backup table?Hi,
Why won't you push the creation of the backup out of the loop ?
declare
v_stmt varchar2(1000);
v_date date;
begin
for rec in
(select * from user_tables where table_name like 'CHK_CNFG_DTL_BKP%' )
loop
begin
execute immediate 'alter session set nls_date_format=''DD_MON_YYYY''';
v_stmt := 'drop table '||rec.table_name|| ' purge';
dbms_output.put_line(v_stmt); ----- Drops Old backup table
execute immediate v_stmt;
exception
when others
then
dbms_output.PUT_LINE (rec.table_name||'-'||sqlerrm);
end;
end loop;
select sysdate into v_date from dual;
v_stmt := 'create table CHK_CNFG_DTL_BKP_'||to_date(v_date)||' as select * from CHK_CNFG_DTL';
dbms_output.put_line('Creating Bkp table CHK_CNFG_DTL_BKP_'|| to_date(v_date) );
dbms_output.put_line(v_stmt);
execute immediate v_stmt; --- Creates new Backup table
end; -
Need to execute a anonymous block
Hi guys,
I have one proc like below.
proc_expl(
empid in number,
ename in varchar2,
marks in marks_typ);
marks_type is record type which consists of 3 subjects.
marks_typ(sub1 number, sub2 number, sub3 number)
and i declared with table type this record type.
now I want to execute anonymous block and i am giving parameter values like below:
declare
empid in number,
ename in varchar2,
marks in marks_typ
begin
empid := 123,
ename := 'abc',
marks marks_typ := marks_typ(55,67,78);
proc_expl(
empid => empid,
ename => ename,
marks => marks_typ);
end;
can any one please suggest me why this is not executing properly.
thanks in advance!
Rgds,
LKRTry the below
CREATE OR REPLACE TYPE marks_type IS OBJECT (sub1 NUMBER(10),
sub2 NUMBER(10),
sub3 NUMBER(10)
CREATE OR REPLACE TYPE marks_typ IS TABLE OF marks_type;
CREATE OR REPLACE PROCEDURE proc_expl(empid NUMBER,
ename VARCHAR2,
marks marks_typ
AS
v_marks marks_typ:= marks;
BEGIN
FOR i IN 1..v_marks.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE(v_marks(i).sub1||','||v_marks(i).sub2||','||v_marks(i).sub3);
END LOOP;
END;
SET SERVEROUTPUT ON
DECLARE
empid NUMBER;
ename VARCHAR2(20);
marks marks_typ := marks_typ();
BEGIN
empid := 123;
ename := 'abc';
marks.extend;
marks(1) := marks_type(55,67,78);
proc_expl(empid,ename,marks);
END;
Execution:-
SQL> DECLARE
2 empid NUMBER;
3 ename VARCHAR2(20);
4 marks marks_typ := marks_typ();
5 BEGIN
6 empid := 123;
7 ename := 'abc';
8 marks.extend;
9 marks(1) := marks_type(55,67,78);
10 proc_expl(empid,ename,marks);
11 END;
12 /
55,67,78
PL/SQL procedure successfully completed.
Hope it helps
Maybe you are looking for
-
Report Painter values are not populating for a particular cost center
Report Painter(GR55) values are not populating for a particular cost center for the months of April 1 2011 where as for May onwards values are displaying correctly..We have check the transaction code KSB1 for this cost center there are some values po
-
POA SP3 and Data Synchroniser 1.2.3 Build 882
Hi All, Last week we updated to Groupwise 8 SP3, running on Netware 6.5 with no issues. Since that update we have had major issues with Data Synchroniser 1.2.3 Build 882. Every 2 to 5 hours all the IOS devices ( we only use IOS devices) will throw up
-
Workflow builder that suports j2ee
Plase, anyone tell me where I can find to download for free the best workflow builder that supports j2ee for windows. Thanx
-
Error when trying to open from Sharepoint
We have moved our project to SharePoint. From Windows, I navigated to the folder and mapped that drive which is drive X: I tried to open a RoboHelp project from the X: drive and I got the following error: "The path X:.... is too long and will be dele
-
Different message type received. How?
Hi Experts, Its sap to sap integration through xi.The message type send from sender sap is hrmd_a but at receiver side it is received as hrmd_b as a result idoc failed with 51 status (error-> there are no entries available in the distribution model