Calling a procedure that has a refcursor as out parameter - sql

I created a package as follows :
create or replace package apps.xx_sal
as
PROCEDURE SAL_HIST_C(p_person_id IN NUMBER
,p_success OUT VARCHAR2
,p_sql OUT VARCHAR2
,p_cur OUT SYS_REFCURSOR)
IS
l_success VARCHAR2(32000) := 'OK';
l_sql VARCHAR2(32767);
l_sql_empty VARCHAR2(32767);
l_step VARCHAR2(1000);
l_query_length PLS_INTEGER := 0;
c_process CONSTANT VARCHAR2(200) := 'SAL_HIST_C';
BEGIN
l_step := c_process || ' :: BUILD EMPTY SQL';
--
l_sql_empty := ' SELECT person_id
,pay_basis_id
,change_date
from apps.salary_hist_v
WHERE 1 = 2 ';
--
--
l_step := c_process || ' :: BUILD SQL';
--
l_sql :=
'
SELECT paf.person_id
,paf.pay_basis_id
,ppp.change_date change_date
FROM hr.per_pay_proposals ppp
,per_all_assignments_f paf
WHERE paf.primary_flag = ''Y''
AND ppb.pay_basis_id = paf.pay_basis_id
AND paf.person_id = :l_person_id ';
--
-- check sql query
l_query_length := LENGTH(l_sql);
--DBMS_OUTPUT.put_line ('Length of EXECUTED SQL := ' || l_query_length);
-- open cursor with bind variables applied
--
l_step := c_process || ' :: OPEN CURSOR with BIND VARIABLE APPLIED';
--
OPEN p_cur FOR l_sql USING p_person_id;
l_success := 'OK';
p_sql := l_sql;
p_success := l_success;
EXCEPTION
WHEN OTHERS
THEN
l_success := 'ERROR :: ' || l_step || CHR(10) || SQLERRM || CHR(10) || DBMS_UTILITY.format_error_backtrace;
p_sql := l_sql;
p_success := l_success;
OPEN p_cur FOR l_sql_empty;
END SAL_HIST_C;
Now when I am passing the parameter to see the output an error occurs:
DECLARE
--l_person_id number;
l_success VARCHAR2(32000) ;
l_sql VARCHAR2(32767);
l_cur sys_refcursor;
BEGIN
APPS.xx_sal.SAL_HIST_C (
person_id=>4816,
p_success => l_success,
p_sql=>l_sql,
p_cur => :l_cur);
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Output Returned from Proc :: ' || l_success);
DBMS_OUTPUT.PUT_LINE ('SQL Executed for the GRID :: ' || l_cur);
END;
Error:
[Error] Execution (10: 3): ORA-06550: line 10, column 3:
PLS-00306: wrong number or types of arguments in call to 'SAL_HIST_C'
ORA-06550: line 10, column 3:
PL/SQL: Statement ignored
ORA-06550: line 18, column 23:
PLS-00306: wrong number or types of arguments in call to '||'
ORA-06550: line 18, column 1:
PL/SQL: Statement ignored
I don't know why is the error happens. I am executing in Toad. I think I am not calling the procedure in the anonymous block correctly

#user3809240
There are two ORA errors in your message.
1. PLS-00306: wrong number or types of arguments in call to 'SAL_HIST_C'
Replace
APPS.xx_sal.SAL_HIST_C (person_id=>4816, p_success => l_success, p_sql=>l_sql,p_cur => :l_cur);
with
APPS.xx_sal.SAL_HIST_C (4816, l_success, l_sql,l_cur);
2. PLS-00306: wrong number or types of arguments in call to '||'
We cannot do a console output of refcursor. Comment out the below line and then re-run your caller program.
DBMS_OUTPUT.PUT_LINE ('SQL Executed for the GRID :: ' || l_cur);
Now, it should work perfectly.
Cheers,
Madhu.
PS : Please mark this post as ANSWER if my solution works. :)

Two things I can see wrong:
Your stored procedure has a parameter named p_person_id, but you are calling it with a parameter named person_id instead.
You cannot concatenate a string and a ref cursor. If you want to display the values that came out of the ref cursor, you will have to repeatedly fetch values from the cursor, displaying each row, until there aren't any left.
Incidentally I don't see the point of the COMMIT, as there's no data you're inserting, updating or deleting.

Related

Passing table name and column name dynamically to PL/SQL Stored procedure

I am trying to pass table name and column name to a stored procedure in oracle , but it gives me following error: table or view does not exist
Below is the code:
create or replace procedure jz_dynamic_sql_statement
(p_table_name in varchar2,
p_col1_name in varchar2,
p_check_result out integer)
as
v_error_cd est_runtime_error_log.error_cd%type;
v_error_msg est_runtime_error_log.error_msg%type;
v_sql varchar2(1024);
v_result number(10);
begin
v_result := 0;
v_sql := 'select count(*) from ' || p_table_name ||' WHERE COLUMNNAME=' || p_col1_name;
execute immediate v_sql into v_result;
p_check_result := v_result;
end;
If the error coming back says the table does not exist then that means the table you pass in does not exist or the user that the procedure runs under cannot access it.
You could add a dbms_output.put_line statement to display the query that you are building and then try running it yourself, before you attempt the execute immediate. Then you know what errors you need to fix.
dbms_output.put_line('query : '||v_sql);
Be sure to turn on dbms_output.
Also, from what it looks like you are trying to do, you will need to pass the column name AND column value. Unless the tables you are querying will ALWAYS have the column name "COLUMNNAME".
Try this:
v_sql := 'select count(*) from ' || p_table_name ||' WHERE COLUMNNAME=''' || p_col1_name|| '''';

How to execute a local procedure using execute immedate?

I have the below PL SQL Block:
WHENEVER SQLERROR EXIT 1
SET SERVEROUTPUT ON
DECLARE
v_sql VARCHAR2(500);
f1 VARCHAR2(20) := 'abc';
p_procname VARCHAR2 (30) := 'OPENLOG';
PROCEDURE OPENLOG (file_name IN VARCHAR2)
IS
BEGIN
NULL;
END;
BEGIN
DBMS_OUTPUT.PUT_LINE('Begin');
v_sql := 'BEGIN ' || p_procname || '(:a); END;';
EXECUTE IMMEDIATE v_sql USING IN f1;
END;
/
When I execute the above block, I get the error:
DECLARE
*
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00201: identifier 'OPENLOG' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
ORA-06512: at line 19
However, if the procedure OPENLOG is part of a package, then it works fine.
Please advise how to execute a local procedure using dynamic SQL.
As Amarillo said you can't execute a locally-defined procedure dynamically, as it doesn't exist in the SQL scope the dynamic section will be using.
The situation you describe is that all the procedures are defined in the anonymous block's DECLARE section and you are running a query that tells you which of them to execute - and presumably which also gives you the arguments to pass. You can just use an if/else construct or a case statement to execute the appropriate procedures, something like:
DECLARE
...
BEGIN
FOR data IN (SELECT procname, arg1, arg2, ... from <your_query>) LOOP
CASE data.procname
WHEN 'OPENLOG' THEN
openlog(data.arg1);
WHEN 'WRITELOG' THEN
writelog(data.arg1, data.arg2);
WHEN ...
...
ELSE
-- handle/report an invalid procedure name
-- or skip the `ELSE` and let CASE_NOT_FOUND be thrown
END CASE;
END LOOP;
END;
/
You just need one WHEN condition and appropriate procedure call for each procedure. You can also either have an ELSE to catch any unexpected procedure names or let the CASE_NOT_FOUND exception (ORA-06592) be thrown, depending on what you need to happen if that ever occurs.
Use it like this:
DECLARE
v_sql VARCHAR2(500);
f1 VARCHAR2(20) := 'abc';
p_procname VARCHAR2 (30) := 'OPENLOG';
PROCEDURE OPENLOG (file_name IN VARCHAR2)
IS
BEGIN
NULL;
END;
BEGIN
DBMS_OUTPUT.PUT_LINE('Begin');
openlog(f1);
END;
You don't need to use execute immediate with begin end in this case, because you have the procedure in the declare section.
The other way is create the procedure as a database object like this:
CREATE PROCEDURE OPENLOG (file_name IN VARCHAR2)
IS
BEGIN
NULL;
END;
And the you can use execute immediate:
DECLARE
v_sql VARCHAR2(500);
f1 VARCHAR2(20) := 'abc';
p_procname VARCHAR2 (30) := 'OPENLOG';
BEGIN
DBMS_OUTPUT.PUT_LINE('Begin');
v_sql := 'BEGIN ' || p_procname || '(:a); END;';
EXECUTE IMMEDIATE v_sql USING IN f1;
END;

Unable to run dynamic query in stored procedure while selecting count of records

Hi I am trying to simply get the count of data in source table.
CREATE OR REPLACE PROCEDURE MOVE_CHECK (SCHEMA_SOURCE IN VARCHAR2,
SCHEMA_TARGET IN VARCHAR2,
TABLE_SOURCE IN VARCHAR2,
TABLE_TARGET IN VARCHAR2,
COLUMN_SOURCE IN VARCHAR2,
COLUMN_TARGET IN VARCHAR2)
AS
A VARCHAR2 (30);
B VARCHAR2 (30);
C VARCHAR2 (30);
D VARCHAR2 (30);
E VARCHAR2 (30);
F VARCHAR2 (30);
Count_source NUMBER (38);
TEMP_1 VARCHAR2 (100);
BEGIN
A := SCHEMA_SOURCE;
B := SCHEMA_TARGET;
C := TABLE_SOURCE;
D := TABLE_TARGET;
E := COLUMN_SOURCE;
F := COLUMN_TARGET;
TEMP_1 :=
'select count ( ' || E || ' ) into Count_source from ' || C || ';';
DBMS_OUTPUT.PUT_LINE ('STARTED');
DBMS_OUTPUT.PUT_LINE (TEMP_1);
EXECUTE IMMEDIATE (TEMP_1);
DBMS_OUTPUT.PUT_LINE ('source_count:' || Count_source);
DBMS_OUTPUT.PUT_LINE ('END');
END MOVE_CHECK;
I am getting
Connecting to the database
ORA-00911: invalid character
ORA-06512: at "YDSCST.MOVE_CHECK", line 31
ORA-06512: at line 16
Can any one help me on this ?
I am trying to code a procedure where i can test if all the data are completely moved from source to target table.
Your dynamic statement should not have a semicolon at the end; that is a statement separator and not relevant or valid for a single statement. You can only run a single SQL statement dynamically anyway (unless you put several into an anonymous PL/SQL block).
Your into is in the wrong place too:
TEMP_1 := 'select count ( '|| E ||' ) from ' || C;
DBMS_OUTPUT.PUT_LINE ('STARTED');
DBMS_OUTPUT.PUT_LINE (TEMP_1);
EXECUTE IMMEDIATE TEMP_1 INTO Count_source;
Not sure why you're bothering to have and assign local variables when you can use the procedure arguments directly, which I think makes the statement more readable:
TEMP_1 := 'select count ( '|| COLUMN_SOURCE ||' ) from ' || TABLE_SOURCE;

How do I view a CLOB output parameter in TOAD from an Oracle Stored Procedure?

I have a stored procedure in a package in an Oracle database that has 2 input parameters + 1 output CLOB parameter. How do I view the output in Toad? (Preferably with the user only having execute/select permissions)
Solution:
DECLARE
my_output_parameter CLOB;
BEGIN
my_package.my_stored_proc(1, 2, my_output_parameter);
DBMS_OUTPUT.PUT_LINE(my_output_parameter);
END;
Don't forget to execute as script, rather than just execute statement, and results appear in the DBMS Output window, not the datagrid.
I guess DBMS_OUTPUT.PUT_LINE has an internal line limit of 255 chars. However it has been removed from 10g Release 2 onwards. You can try inserting the column data in a table and view it later on by querying that table.
Please refer -
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:146412348066
Would you consider printing the CLOB as a result set? You could then use a PIPELINED function (more about them here: PIPELINED functions by Tim Hall) which would return the CLOB line by line, take a look at the example below:
CREATE TABLE my_clob_tab (
id NUMBER,
clob_col CLOB
)
/
INSERT INTO my_clob_tab
VALUES (1,
to_clob('first line' || chr(10) ||
'second line, a longer one' || chr(10) ||
'third'))
/
CREATE OR REPLACE TYPE t_my_line_str AS TABLE OF VARCHAR2(2000)
/
CREATE OR REPLACE FUNCTION print_clob_func(p_id IN NUMBER)
RETURN t_my_line_str PIPELINED
AS
v_buffer VARCHAR2(32767);
v_clob CLOB;
v_len NUMBER;
v_offset NUMBER := 1;
v_line_break_pos NUMBER;
v_amount NUMBER;
BEGIN
SELECT clob_col
INTO v_clob
FROM my_clob_tab
WHERE id = p_id;
IF v_clob IS NOT NULL THEN
v_len := dbms_lob.getlength(v_clob);
WHILE v_offset < v_len
LOOP
v_line_break_pos := instr(v_clob, chr(10), v_offset);
IF v_line_break_pos = 0 THEN
v_amount := v_len - v_offset + 1;
ELSE
v_amount := v_line_break_pos - v_offset;
END IF;
dbms_lob.read(v_clob, v_amount, v_offset, v_buffer);
v_offset := v_offset + v_amount + 1;
PIPE ROW (v_buffer);
END LOOP;
END IF;
END;
/
(the function can be changed so that it takes as a parameter the CLOB you get from your procedure)
The code reads the content of the CLOB line by line (I assumed that the line separator is CHR(10) - if you are on Windows, you can change it to CHR(10) || CHR(13)) and PIPEs each line to the SELECT statement.
The function that reads the clob could also print the output to the standard output via dbms_output.put_line, but it would be trickier, because you'd have to take into account that standard output's maximal line length is limitied to, correct me if I'm wrong, 2000 characters, but it is doable (can't try that solution right now, unfortunately). In the meanwhile, please check above proposal and give me some feedback if that would work for you.
Back to the solution, now we can issue this SELECT statement:
SELECT COLUMN_VALUE AS clob_line_by_line FROM TABLE(print_clob_func(1));
Which will give us the following output:
CLOB_LINE_BY_LINE
-------------------------
first line
second line, a longer one
third
Check it at SQLFiddle: SQLFiddle example
Approach with inserting PL/SQL block and dbms_output:
DECLARE
my_output_parameter CLOB;
BEGIN
my_package.my_stored_proc(1, 2, my_output_parameter);
declare
vClob CLOB := my_output_parameter;
vPos number;
vLen number;
begin
vLen := DBMS_LOB.GetLength(vClob);
vPos := 1;
while vPos < vLen loop
DBMS_OUTPUT.Put(DBMS_LOB.Substr(vCLOB, 200, vPos));
vPos := vPos + 200;
end loop;
DBMS_OUTPUT.new_line;
end;
END;

can TYPE be declared of ref cursor rowtype

TYPE ref_cur IS REF CURSOR;
ref_cur_name ref_cur;
TYPE tmptbl IS TABLE OF ref_cur_name%ROWTYPE;
n_tmptbl tmptbl;
I tried this code but can't get it thru compiler . Is there a way to store the results of ref cursor into a table ?
NOTE-I need a table because i need to access the column of ref cursor . Using dbms_sql to access records of ref cursor is a bit tough for me .
UPDATE :
/* Formatted on 8/1/2013 4:09:08 PM (QP5 v5.115.810.9015) */
CREATE OR REPLACE PROCEDURE proc_deduplicate (p_tblname IN VARCHAR2,
p_cname IN VARCHAR2,
p_cvalue IN VARCHAR2)
IS
v_cnt NUMBER;
TYPE ref_cur IS REF CURSOR;
ref_cur_name ref_cur;
v_str1 VARCHAR2 (4000);
v_str2 VARCHAR2 (4000);
v_str3 VARCHAR2 (4000);
BEGIN
v_str1 :=
'SELECT ROWID v_rowid FROM '
|| p_tblname
|| ' WHERE '
|| p_cname
|| '='''
|| p_cvalue
|| '''';
BEGIN
v_str2 :=
'SELECT COUNT ( * )
FROM '
|| p_tblname
|| ' WHERE '
|| p_cname
|| ' = '''
|| p_cvalue
|| '''';
logerrors ('proc_deduplicate',
'count exception',
SQLCODE,
v_str2 || SQLERRM,
'e');
EXECUTE IMMEDIATE v_str2 INTO v_cnt;
EXCEPTION
WHEN OTHERS
THEN
logerrors ('proc_deduplicate',
'count exception',
SQLCODE,
SQLERRM,
'e');
END;
IF v_cnt IS NOT NULL
THEN
OPEN ref_cur_name FOR v_str1;
LOOP
IF v_cnt = 1
THEN
EXIT;
ELSE
BEGIN
v_str3 :=
'DELETE FROM '
|| p_tblname
|| ' WHERE ROWID = v_rowid ';
-- THIS IS THE PROBLEM . i just created an alias above for rowid keyword but i guess, DBMS sql will have to be used after all .
EXECUTE IMMEDIATE v_str3;
EXCEPTION
WHEN OTHERS
THEN
logerrors (
' proc_deduplicate
',
' delete exception
',
SQLCODE,
SQLERRM,
' e
'
);
END;
END IF;
v_cnt := v_cnt - 1;
END LOOP;
END IF;
EXCEPTION
WHEN OTHERS
THEN
logerrors (
' proc_deduplicate',
' final exception
',
SQLCODE,
SQLERRM,
' e'
);
END;
/
By issuing TYPE ref_cur IS REF CURSOR you are declaring a weak cursor. Weak cursors return no specified types. It means that you cannot declare a variable that is of weak_cursor%rowtype, simply because a weak cursor does not return any type.
declare
type t_rf is ref cursor;
l_rf t_rf;
type t_trf is table of l_rf%rowtype;
l_trf t_trf;
begin
null;
end;
ORA-06550: line 4, column 27:
PLS-00320: the declaration of the type of this expression is incomplete or malformed
ORA-06550: line 4, column 3:
PL/SQL: Item ignored
If you specify return type for your ref cursor, making it strong, your PL/SQL block will compile successfully:
SQL> declare -- strong cursor
2 type t_rf is ref cursor return [table_name%rowtype][structure];
3 l_rf t_rf;
4 type t_trf is table of l_rf%rowtype;
5 l_trf t_trf;
6 begin
7 null;
8 end;
9 /
PL/SQL procedure successfully completed
As far as I understand what you're doing, you just need to parameterise the delete:
...
v_str3 VARCHAR2 (4000);
v_rowid ROWID;
BEGIN
...
OPEN ref_cur_name FOR v_str1;
LOOP
FETCH ref_cur_name INTO v_rowid;
EXIT WHEN ref_cur_name%NOTFOUND;
IF v_cnt = 1
THEN
EXIT;
ELSE
BEGIN
v_str3 :=
'DELETE FROM '
|| p_tblname
|| ' WHERE ROWID = :v_rowid ';
EXECUTE IMMEDIATE v_str3 USING v_rowid;
...
You need to fetch the ref_cur_name into a variable, which needs to be declared obviously, and then use that as a bind variable value in the delete.
You should do the same thing with the p_cvalue references in the other dynamic SQL too. You could probably make this much simpler, with a single delete and no explicit count, in a single dynamic statement:
CREATE OR REPLACE PROCEDURE proc_deduplicate (p_tblname IN VARCHAR2,
p_cname IN VARCHAR2,
p_cvalue IN VARCHAR2)
IS
BEGIN
execute immediate 'delete from ' || p_tblname
|| ' where ' || p_cname || ' = :cvalue'
|| ' and rowid != (select min(rowid) from ' || p_tblname
|| ' where ' || p_cname || ' = :cvalue)'
using p_cvalue, p_cvalue;
END proc_deduplicate;
/
SQL Fiddle.
If you wanted to know or report how many rows were deleted, you could refer to SQL%ROWCOUNT after the execute immediate.
Strong ref cursor returns defined values, but weak is free to anything, totally dynamic.
But we can't define rowtype variable on weak ref cur
e.g.
declare
refcur sys_refcursor;
emprec refcur%rowtype; --it'll yield error
while
declare
type empref is ref cursor returns employees%rowtype;
empcur empref;
emprec empcur%rowtype; --it'll work fine.
This is very useful, now we can define collection on them and many other advantage if you talk about practically.
No. You're trying to declare the type against an instance of the cursor anyway, so you'd be closer with:
TYPE tmptbl IS TABLE OF ref_cur%ROWTYPE;
but you still can't do that, you'd get PLS-00310: with %ROWTYPE attribute, 'REF_CUR' must name a table, cursor or cursor-variable.
A ref cursor is weakly-typed, so the compiler doesn't know what a record would look like. You could open the ref cursor for different results depending on the logic in the block, or a dynamic query, and the compiler would have no way to know what to expect in advance.
The PL/SQL documentation state that %rowtype can apply to an explicit cursor, a strong cursor variable, or a table or view. And this compares strong and weak cursor variables.
If you know what your query will be you can declare a record type with those fields, or against a table %rowtype if you're be querying a single table. Since you're using dbms_sql I guess you won't know that though. Maybe if you updated your question with more information about what you're actually trying to do there would be some other approaches you could try.