Oracle DB: how to store function result into variable inside procedure - oracle

Good day. I have a function:
create function get_n(search tt.pp%type)
return number
is rc number;
begin
select count(*)
into rc
from tt
where tt.pp=search;
return (rc);
end;
/
and i can get result as
variable qwe number;
begin
select get_n('sample')
into :qwe
from dual;
end;
print qwe;
So, it's successfully works. But by parts: i can't exec line with print at execution of other (PLS-00103: Encountered the symbol "PRINT"...). And it's really strange.
I try to get result from function in anonymous block and print it:
declare
qwe number;
begin
select get_n('sample')
into :qwe
from dual;
dbms_output.put_line(qwe);
exception
when others
then dbms_output.put_line(sqlerrm);
end;
/
And it's not print anything. Why?

Problem is :. Following code should work:
declare
qwe number;
begin
select get_n('sample')
into qwe
from dual;
dbms_output.put_line(qwe);
exception
when others
then dbms_output.put_line(sqlerrm);
end;
/
: means variable that need to be binded not variable inside PL/SQL block.
And in case of first block you're missing / after PL/SQL block what causes compiler reads print as part of PL/SQL not SQLplus script:
variable qwe number;
begin
select get_n('sample')
into :qwe
from dual;
end;
/
print qwe;

Related

Execute PROCEDURE on Oracle PL/SQL with DECLARE variable

I just currently learning about Oracle PL/SQL. I wanna create store procedure with variable and then call it with another script. Is it possible?
I tried use simple script without variable and it works:
CREATE OR REPLACE PROCEDURE testmyproc AS
BEGIN
INSERT INTO tes_table(dt)
VALUES (sysdate);
commit;
END testmyproc;
Then I call it with another script abc.sql
begin
testmyproc;
end;
It works successfully.
But, unfortunately if I use DECLARE (variable) at my PROCEDURE, it show error when I execute (but it success in create procedure).
Here's my PROCEDURE (no error):
CREATE OR REPLACE PROCEDURE sp_testmyproc AS
DECLARE
job_name varchar(100);
status_key number;
status_desc varchar(100);
notes varchar(250);
BEGIN
status_key := 1;
status_desc := 'SUCCESS';
notes := 'Process Completed';
INSERT INTO automation_log(job_name, dt, status_key, status_desc, notes)
VALUES (job_name, sysdate, status_key, status_desc, notes);
commit;
END sp_testmyproc;
Here's my execure script abc.sql (show error when i execute it)
-without DECLARE
begin
sp_testmyproc;
end;
-I tried to execute it with DECLARE
DECLARE
job_name varchar(100);
status_key number;
status_desc varchar(100);
notes varchar(250);
begin
status_key := 1;
status_desc := 'SUCCESS';
notes := 'Process Completed';
sp_testmyproc;
end;
It show error like this:
> ORA-06550: line 8, column 11:
> PLS-00905: SP_TESTMYPROC is invalid
> ORA-06550: line 8, column 3:
> PL/SQL: Statement ignored
Can I call Procedure for another script? Is It best practice?
I just think PROCEDURE can be used for many cases (something like function in programming).
Thank you!
You need to learn the syntax of the procedure.
In Procedure, You should not use the keyword DECLARE. Any variables you want to declare must be between AS and BEGIN in the procedure.
Your procedure should look like follows:
CREATE OR REPLACE PROCEDURE sp_testmyproc AS
--DECLARE
job_name varchar(100);
status_key number;
status_desc varchar(100);
notes varchar(250);
BEGIN
status_key := 1;
.....
.....
.....
Refer to this document for the syntax of the oracle procedure as it is very easy to follow.
Please note the difference when creating a stored procedure in SQL*Plus:
SQL> create or replace procedure test_ok as
2 v number;
3 begin
4 v:=0;
5 end;
6 /
Procedure created.
SQL> show errors
No errors.
SQL> create or replace procedure test_ko as
2 declare
3 v number;
4 begin
5 v:=0;
6 end;
7 /
Warning: Procedure created with compilation errors.
SQL> show errors
Errors for PROCEDURE TEST_KO:
LINE/COL ERROR
-------- -----------------------------------------------------------------
2/1 PLS-00103: Encountered the symbol "DECLARE" when expecting one of
the following:
begin function pragma procedure subtype type <an identifier>
<a double-quoted delimited-identifier> current cursor delete
exists prior external language
SQL>
If you have compilation errors you get at least Warning: Procedure created with compilation errors. If you have compilation errors and use show errors you get all error messages.

Create Oracle sequence via execute immediate without pipe || operator

create sequence s1 ;
declare
v_value number;
v_sql_stmt varchar2(4000);
v_seq_name varchar2(30);
BEGIN
v_seq_name:='S1'; -- **this is dynamic and the sequence will be passed in the proc as input parameter at runtime**
v_sql_stmt:= 'select :v_seq_name'||'.nextval from dual' ;
EXECUTE IMMEDIATE v_sql_stmt INTO v_value USING v_seq_name ;
--**below is working but I dont want to do in this way because of sql injection issue, let me know how to fix the above**
--EXECUTE IMMEDIATE 'select ' || v_seq_name || '.nextval from dual' INTO v_value;
dbms_output.put_line(v_value);
end;
/
the above code is throwing error, please help to fix.
If you run the commented code then it will run but I dont want to use || in execute immediate. I want to use colon : only.
the sequence name will be passed at run time. The above code will be converted to a proc later.
I understand your concern about SQL injection. To my knowledge, table/column/sequence names cannot be specified with bind variables. However, you could do a simple check before executing the unsafe code:
CREATE SEQUENCE s1;
CREATE SEQUENCE s2;
CREATE OR REPLACE FUNCTION p(seq_name VARCHAR2) RETURN NUMBER AS
v_value number;
v_sql_stmt varchar2(4000);
v_seq_name varchar2(128 BYTE);
BEGIN
v_seq_name:= DBMS_ASSERT.SIMPLE_SQL_NAME(seq_name);
v_sql_stmt:= 'select '||v_seq_name||'.nextval from dual';
EXECUTE IMMEDIATE v_sql_stmt INTO v_value;
RETURN v_value;
END p;
/
If a valid name is used, everything works as expected:
select p('s1') from dual;
1
select p('s2') from dual;
2
However, if seq_name is not a valid Oracle name, DBMS_ASSERT throws an exception:
select p('1; DROP TABLE x') from dual;
ORA-44003: invalid SQL name
ORA-06512: at "SYS.DBMS_ASSERT", line 215
ORA-06512: at "WFL.P", line 6
44003. 0000 - "invalid SQL name"

Procedure gives empty result when called

I have created a simple procedure to reverse a number in PL/SQL. The procedure executes fine, but the result doesn't get print. Here's the proc,
CREATE OR REPLACE PROCEDURE SAMPLE_REV (myinput IN NUMBER, finalresult OUT NUMBER)
IS
OperInput NUMBER;
MYREMAINDER NUMBER;
MYRESULT NUMBER;
BEGIN
OperInput:=myinput;
while OperInput!=0 LOOP
MYREMAINDER:=mod(OperInput,10);
MYRESULT:=(MYRESULT*10)+MYREMAINDER;
OperInput:=TRUNC(OperInput/10);
end LOOP;
finalresult:=MYRESULT;
END;
Procedure, when executed works fine. But, when I call on the procedure by the following code,
DECLARE
ENTER NUMBER;
finalresult NUMBER;
BEGIN
ENTER:=&ENTER;
SAMPLE_REV(ENTER,finalresult);
dbms_output.put_line('Output is '|| finalresult);
END;
The result is empty as,
Output is
PL/SQL procedure successfully completed.
I can't come to know the error here, if any. And thanks for the help.
the procedure is using MYRESULT before it is initialized hence null. So this line:
MYRESULT:=(MYRESULT*10)+MYREMAINDER;
is essentially
MYRESULT:=(<<<NULL>>>*10)+MYREMAINDER;
So null overall.
Just adding a :=0 to the declaration will get it working. Also add the set serveroutput on
SQL>set serveroutput on
SQL>CREATE OR REPLACE PROCEDURE SAMPLE_REV (myinput IN NUMBER, finalresult OUT NUMBER)
2 IS
3 OperInput NUMBER;
4 MYREMAINDER NUMBER;
5 MYRESULT NUMBER :=0;
6 BEGIN
7 OperInput:=myinput;
8
9 while OperInput!=0 LOOP
10
11 MYREMAINDER:=mod(OperInput,10);
12 MYRESULT:=(MYRESULT*10)+MYREMAINDER;
13 OperInput:=TRUNC(OperInput/10);
14
15 end LOOP;
16
17 finalresult:=MYRESULT;
18
19 END;
20* /
Procedure SAMPLE_REV compiled
SQL>DECLARE
2 ENTER NUMBER;
3 finalresult NUMBER;
4 BEGIN
5 ENTER:=&ENTER;
6 SAMPLE_REV(ENTER,finalresult);
7 dbms_output.put_line('Output is '|| finalresult);
8 END;
9 /
Enter value for ENTER: 987
Output is 789
PL/SQL procedure successfully completed.
SQL>
In order to view the output of a PL/SQL procedure using dbms_ouput.put_line, run the following command in your session window:
SET SERVEROUTPUT ON;
Should do the trick :)
I see your calculation is not correct. I have added additional output in the procedure to see what it is printing.
MYRESULT itslef is empty and hence you see the output is empty.
set serveroutput on;
CREATE OR REPLACE PROCEDURE SAMPLE_REV (myinput IN NUMBER, finalresult OUT NUMBER)
IS
OperInput NUMBER;
MYREMAINDER NUMBER;
MYRESULT NUMBER;
BEGIN
OperInput:=myinput;
while OperInput!=0 LOOP
MYREMAINDER:=mod(OperInput,10);
dbms_output.put_line('remainder ' || MYREMAINDER);
dbms_output.put_line('in ' || MYRESULT);
MYRESULT:=(MYRESULT*10)+MYREMAINDER;
dbms_output.put_line('out ' || MYRESULT);
OperInput:=TRUNC(OperInput/10);
end LOOP;
finalresult:=MYRESULT;
END;
This line is the problem:
MYRESULT:=(MYRESULT*10)+MYREMAINDER;
On the first iteration MYRESULT is null. So the MYRESULT*10 will be also null. And null + MYREMAINDER = null;
Initialize MYRESULT in the declare section to 0;

PL/SQL numeric value or error: confusion with functions and procedures (Oracle PL/SQL)

I previously asked a question in stackoverflow regarding a certain function that I was having a hard time with and I found the answer when I saw the RETURN statement missing.
Now, I am dealing with a procedure that calls for the input text letters to be converted to UPPER if in the LOWER case and vice versa.
e.g IF I put in 'AbC' it should return 'aBc'
So far this is my code
CREATE OR REPLACE PROCEDURE Opposite_Case (p_string IN VARCHAR2)
IS
var_string VARCHAR2(20);
var_contain VARCHAR2(20);
i NUMBER;
BEGIN
var_string:=substr(Opposite_Case.p_string,i,1);
var_contain:= var_string || var_contain;
FOR i in 1.. length(var_string)
LOOP
BEGIN
IF var_string IN ('ABCDEFGHIJKLMNOPQRSTUVWXYZ') THEN
SELECT LOWER(var_string) INTO var_contain FROM dual;
ELSE
SELECT UPPER(var_string) INTO var_contain FROM dual;
END IF;
END;
END LOOP;
END;
/
BUT the following error is returned:
EXECUTE Opposite_Case('AbC')
begin Opposite_Case('AbC'); end;
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at "SYS.OPPOSITE_CASE", line 10
ORA-06512: at line 1
Thanks in advance.
PS. This is just my 3rd day with a PL/SQL language so please bear with me.
EDIT: I got it to work finally thanks to #Satya's help. Now I get to convert them like it should but how do I output my selects in one line though?
I'm almost there. Appreciate the help a lot from this community!!
What I have so far:
SQL> EXECUTE Opposite_Case('AbC')
A
b
C
PL/SQL procedure successfully completed
You should investigate the TRANSLATE function. To use it to switch the case of the characters in your string you'd do something like the following:
SELECT TRANSLATE('AbC',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
FROM DUAL;
which should return 'aBc'.
SQLFiddle here
Share and enjoy.
Finally found the answer! Thanks guys! (without TRANSLATE though)!
CREATE OR REPLACE PROCEDURE Opposite_Case (p_string IN VARCHAR2)
IS
var_string VARCHAR2(20);
var_contain VARCHAR2(20);
i NUMBER;
BEGIN
FOR i in 1.. length(p_string)
LOOP
BEGIN
var_string:=substr(p_string,i,1);
var_contain:= var_string;
IF var_string IN ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z') THEN
SELECT LOWER(var_string) INTO var_contain FROM dual;
DBMS_OUTPUT.PUT(var_contain);
ELSE
SELECT UPPER(var_string) INTO var_contain FROM dual;
DBMS_OUTPUT.PUT(var_contain);
END IF;
END;
END LOOP;
dbms_output.new_line;
END;
/

Run Stored Procedure in SQL Developer?

I am trying to run a stored procedure that has multiple in and out parameters. The procedure can only be viewed in my Connections panel by navigating
Other Users | <user> | Packages | <package> | <procedure>
If I right click , the menu items are "Order Members By..." and "Create Unit Test" (greyed out). The ability to "Run" the procedure does not seem possible when it's accessed by user.
I have been trying to find an example of how to create an anonymous block so that I can run the procedure as a SQL file, but haven't found anything that works.
Does anyone know how I can execute this procedure from SQL Developer? I am using Version 2.1.1.64.
EDIT 1:
The procedure I want to call has this signature:
user.package.procedure(
p_1 IN NUMBER,
p_2 IN NUMBER,
p_3 OUT VARCHAR2,
p_4 OUT VARCHAR2,
p_5 OUT VARCHAR2,
p_6 OUT NUMBER)
If I write my anonymous block like this:
DECLARE
out1 VARCHAR2(100);
out2 VARCHAR2(100);
out3 VARCHAR2(100);
out4 NUMBER(100);
BEGIN
EXECUTE user.package.procedure (33,89, :out1, :out2, :out3, :out4);
END;
I get the error:
Bind Varialbe "out1" is NOT DECLCARED
anonymous block completed
I've tried initializing the out* variables:
out1 VARCHAR2(100) := '';
but get the same error:
EDIT 2:
Based on Alex's answer, I tried removing the colons from in front of the params and get this:
Error starting at line 1 in command:
DECLARE
out1 VARCHAR2(100);
out2 VARCHAR2(100);
out3 VARCHAR2(100);
out4 NUMBER(100);
BEGIN
EXECUTE user.package.procedure (33,89, out1, out2, out3, out4);
END;
Error report:
ORA-06550: line 13, column 17:
PLS-00103: Encountered the symbol "USER" when expecting one of the following:
:= . ( # % ; immediate
The symbol ":=" was substituted for "USER" to continue.
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
With simple parameter types (i.e. not refcursors etc.) you can do something like this:
SET serveroutput on;
DECLARE
InParam1 number;
InParam2 number;
OutParam1 varchar2(100);
OutParam2 varchar2(100);
OutParam3 varchar2(100);
OutParam4 number;
BEGIN
/* Assign values to IN parameters */
InParam1 := 33;
InParam2 := 89;
/* Call procedure within package, identifying schema if necessary */
schema.package.procedure(InParam1, InParam2,
OutParam1, OutParam2, OutParam3, OutParam4);
/* Display OUT parameters */
dbms_output.put_line('OutParam1: ' || OutParam1);
dbms_output.put_line('OutParam2: ' || OutParam2);
dbms_output.put_line('OutParam3: ' || OutParam3);
dbms_output.put_line('OutParam4: ' || OutParam4);
END;
/
Edited to use the OP's spec, and with an alternative approach to utilise :var bind variables:
var InParam1 number;
var InParam2 number;
var OutParam1 varchar2(100);
var OutParam2 varchar2(100);
var OutParam3 varchar2(100);
var OutParam4 number;
BEGIN
/* Assign values to IN parameters */
:InParam1 := 33;
:InParam2 := 89;
/* Call procedure within package, identifying schema if necessary */
schema.package.procedure(:InParam1, :InParam2,
:OutParam1, :OutParam2, :OutParam3, :OutParam4);
END;
/
-- Display OUT parameters
print :OutParam1;
print :OutParam2;
print :OutParam3;
print :OutParam4;
Executing easy. Getting the results can be hard.
Take a look at this question I asked Best way/tool to get the results from an oracle package procedure
The summary of it goes like this.
Assuming you had a Package named mypackage and procedure called getQuestions. It returns a refcursor and takes in string user name.
All you have to do is create new SQL File (file new). Set the connection and paste in the following and execute.
var r refcursor;
exec mypackage.getquestions(:r, 'OMG Ponies');
print r;
For those using SqlDeveloper 3+, in case you missed that:
SqlDeveloper has feature to execute stored proc/function directly, and output are displayed in a easy-to-read manner.
Just right click on the package/stored proc/ stored function, Click on Run and choose target to be the proc/func you want to execute, SqlDeveloper will generate the code snippet to execute (so that you can put your input parameters). Once executed, output parameters are displayed in lower half of the dialog box, and it even have built-in support for ref cursor: result of cursor will be displayed as a separate output tab.
Open the procedure in SQL Developer and run it from there. SQL Developer displays the SQL that it runs.
BEGIN
PROCEEDURE_NAME_HERE();
END;
Use:
BEGIN
PACKAGE_NAME.PROCEDURE_NAME(parameter_value, ...);
END;
Replace "PACKAGE_NAME", "PROCEDURE_NAME", and "parameter_value" with what you need. OUT parameters will need to be declared prior to.
Though this question is quite old, I keep stumbling into same result without finding an easy way to run from sql developer.
After couple of tries, I found an easy way to execute the stored procedure from sql developer itself.
Under packages, select your desired package and right click on the package name (not on the stored procedure name).
You will find option to run. Select that and supply the required arguments. Click OK and you can see the output in output variables section below
I'm using SQL developer version 4.1.3.20
None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:
SET serveroutput on;
DECLARE
testvar varchar(100);
BEGIN
testvar := 'dude';
schema.MY_PROC(testvar);
dbms_output.enable;
dbms_output.put_line(testvar);
END;
And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).
NOTE (differences with mine vs. others):
No : prior to the variable name
No putting .package. or .packages. between the schema name and the procedure name
No having to put an & in the variable's value.
No using print anywhere
No using var to declare the variable
All of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.
Can't believe, this won't execute in SQL Developer:
var r refcursor;
exec PCK.SOME_SP(:r,
'02619857');
print r;
BUT this will:
var r refcursor;
exec TAPI_OVLASCENJA.ARH_SELECT_NAKON_PRESTANKA_REG(:r, '02619857');
print r;
Obviously everything has to be in one line..
Using SQL Developer Version 4.0.2.15 Build 15.21 the following works:
SET SERVEROUTPUT ON
var InParam1 varchar2(100)
var InParam2 varchar2(100)
var InParam3 varchar2(100)
var OutParam1 varchar2(100)
BEGIN
/* Assign values to IN parameters */
:InParam1 := 'one';
:InParam2 := 'two';
:InParam3 := 'three';
/* Call procedure within package, identifying schema if necessary */
schema.package.procedure(:InParam1, :InParam2, :InParam3, :OutParam1);
dbms_output.enable;
dbms_output.put_line('OutParam1: ' || :OutParam1);
END;
/
To run procedure from SQL developer-only execute following command
EXECUTE PROCEDURE_NAME;
I had a stored procedure that returned a cursor, in my case it was actually of a custom package type (T_CURSOR, looks like a convention to me) that is defined as REF CURSOR.
There may be a better way to do this, but I defined variables for all the columns of the table that the cursor was iterating, looped the cursor fetching each row into those variables, then printed them out.
SET serveroutput on;
DECLARE
testvar number;
v_cur SYS_REFCURSOR;
ORIGINAL_EMP_NUM NUMBER;
TEMPORARY_EMP_NUM NUMBER;
ORG_UNIT_CODE VARCHAR2(2 BYTE);
MRU_CODE VARCHAR2(10 BYTE);
CTRL_COMPANY_CODE VARCHAR2(10 BYTE);
IS_TEMP_FLAG VARCHAR2(1 BYTE);
BEGIN
testvar := 420;
foo.updates.get_temporary_authorisations(testvar, v_cur);
dbms_output.enable;
dbms_output.put_line(testvar);
LOOP
FETCH v_cur INTO ORIGINAL_EMP_NUM, TEMPORARY_EMP_NUM, ORG_UNIT_CODE, MRU_CODE, CTRL_COMPANY_CODE, IS_TEMP_FLAG;
EXIT WHEN v_cur%NOTFOUND;
dbms_output.put_line(ORIGINAL_EMP_NUM || ',' || TEMPORARY_EMP_NUM || ',' || ORG_UNIT_CODE || ',' || MRU_CODE|| ',' || CTRL_COMPANY_CODE|| ',' || IS_TEMP_FLAG);
END LOOP;
CLOSE v_cur;
END;
I wasn't able to get #Alex Poole answers working. However, by trial and error, I found the following works (using SQL Developer version 3.0.04). Posting it here in case it helps others:
SET serveroutput on;
DECLARE
var InParam1 number;
var InParam2 number;
var OutParam1 varchar2(100);
var OutParam2 varchar2(100);
var OutParam3 varchar2(100);
var OutParam4 number;
BEGIN
/* Assign values to IN parameters */
InParam1 := 33;
InParam2 := 89;
/* Call procedure within package, identifying schema if necessary */
schema.package.procedure(InParam1, InParam2,
OutParam1, OutParam2, OutParam3, OutParam4);
/* Display OUT parameters */
dbms_output.put_line('OutParam1: ' || OutParam1);
dbms_output.put_line('OutParam2: ' || OutParam2);
dbms_output.put_line('OutParam3: ' || OutParam3);
dbms_output.put_line('OutParam4: ' || OutParam4);
END;
--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;
-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
V_OUT_1 NUMBER;
V_OUT_2 VARCHAR2(200);
BEGIN
--your stored procedure name
schema.package.procedure(
--declaration for in and out parameter
V_OUT_1 => V_OUT_1,
V_OUT_2 => V_OUT_2
);
V_OUT_1 := V_OUT_1;
V_OUT_2 := V_OUT_2;
-- console output, no need to open DBMS OUTPUT seperatly
-- also no need to print each output on seperat line
DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;
Creating Pl/SQL block can be painful if you have a lot of procedures which have a lot of parameters. There is an application written on python that do it for you.
It parses the file with procedure declarations and creates the web app for convenient procedure invocations.
var out_para_name refcursor;
execute package_name.procedure_name(inpu_para_val1,input_para_val2,... ,:out_para_name);
print :out_para_name;

Resources