PL/SQL: Passing an 'array' of strings as argument to sql - oracle

Using plsql, I want to run my test.sql multiple times, each time will pass in a different argument to test.sql and also spool that result to a different file.
The file name may not have a relation with the argument being passed.
I'm hoping I can define two 'arrays'; one for the filename to spool to, and the other for the argument value.
declare
my_types sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll('typeA', 'typeB', 'typeC');
my_filenames sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll('fileNameForA', 'fileNameForB', 'fileNameForC');
begin
for r in my_types.first..my_types.last
loop
--dbms_output.put_line(my_types(r));
--dbms_output.put_line(my_filenames(r));
spool my_filenames(r)
#test.sql my_types(r);
spool off
end loop;
end;
/
For the spool, it says that it encountered symbol "MY_FILENAMES" when it expected := . < # % ;.
Also, it looks like test.sql is taking the argument I put in literally, so 'my_types(r)' instead of the expected 'typeA'. If there is a completely different and easier way of doing this in plsql then let me hear it. Thanks.

To get this to work (clunky, ugly), you have have to use the PLSQL to generate a sql scripts with calls to th esql script(s) you are trying to test. e.g.
set serveroutput on
spool run_it.sql
declare
my_types sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll('typeA', 'typeB', 'typeC');
my_filenames sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll('fileNameForA', 'fileNameForB', 'fileNameForC');
begin
for r in my_types.first..my_types.last
loop
dbms_output.put_line('spool ' || my_filenames(r) );
dbms_output.put_line('#test.sql ' || my_types(r) );
dbms_out.put_line ('spool off' );
end loop;
end;
/
spool off
#run_it.sql
Not tested/compiled. but I hope you get the idea.
With the above run_it.sql should look like:
spool fileNameForA
#test.sql typeA
spool off
spool fileNameForB
#test.sql typeB
spool off
.
.

Related

PL/SQL DB Deployment Script

I'm trying to write a deployment script to run with SQL*Plus in a CI/CD pipeline but I can't find my way around what seems to be a very basic issue.
Here's a shortened version of the script release.sql:
DECLARE
vnum NUMBER;
BEGIN
SELECT COUNT(tname) INTO vnum FROM tab WHERE tname = 'DA_VERSION';
IF vnum = 0 THEN -- run create scripts
#ddl/da_001.sql
#ddl/da_002.sql
#dml/version.sql -- set initial version
END IF;
END;
da_001.sql looks like this:
CREATE TABLE TABLE_NAME
(
COLUMN1 NUMBER NOT NULL
, CONSTRAINT TABLE_NAME_PK PRIMARY KEY
(
COLUMN1
)
ENABLE
);
When I run
sqlplus.exe connection_string #release.sql
I get
CREATE TABLE DA_PRODUCTS
*
ERROR at line 6:
ORA-06550: line 6, column 1:
PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:...
So it doesn't like the CREATE statement at the beginning of da_001.sql but I don't know why. What am I missing here?
Create an installation file for your scripts, ie
install.sql
===========
#ddl/da_001.sql
#ddl/da_002.sql
#dml/version.sql -- set initial version
and then selectively call it via a wrapper in SQL Plus
set feedback off
set pages 0
spool /tmp/runme.sql
select
case when COUNT(tname) = 0 then '##install.sql' else 'pro Skipped install.sql' end
FROM tab WHERE tname = 'DA_VERSION';
spool off
#/tmp/runme.sql
As others have said there is a strict separation between what SQL*PLus understands/is capable of and what is within the SQL and PLSQL languages.
Script handling is one of these distinct areas, which means you cannot executing a SQL script within a PLSQL block.
Also, SQL*Plus does not have any understanding of PLSQL logic constructs.
However, looking at your requirement there might be a way. The answer from #"Connor McDonald" should work. Here is my attempt using a more PLSQL based approach.
This approach uses SQLPLus variables, which can be referenced and amended in both PLSQL and SQLPlus.
First you need a 'No Op' script since when using the SQL*PLus '#' you must specify a valid script name:
noop.sql:
PROMPT No Op
Now your controller script:
-- Declare your variables
VAR script1 VARCHAR2(256)
VAR script2 VARCHAR2(256)
VAR script3 VARCHAR2(256)
DECLARE
vnum NUMBER;
BEGIN
:script1 := 'noop.sql';
:script2 := 'noop.sql';
:script3 := 'noop.sql';
SELECT COUNT(tname) INTO vnum FROM tab WHERE tname = 'DA_VERSION';
IF vnum = 0 THEN -- run create scripts
-- Set variables
:script1 := 'ddl/da_001.sql';
:script2 := 'ddl/da_002.sql';
:script3 := 'dml/version.sql'; -- set initial version
END IF;
END;
/
-- Make variables referencable as SQLPLus defines
COLUMN s1 NEW_VALUE s1
COLUMN s2 NEW_VALUE s2
COLUMN s3 NEW_VALUE s3
SELECT :script1 s1, :script2 s2, :script3 s3
FROM dual;
-- RUN !!
# &&s1
# &&s2
# &&s3
The 3 scriptn variables can be used in PLSQL.
To use as SQL_PLus substition variable (&) we use the COL ... NEW_VALUE command to map a SELECT list column alias to a substituion variable. So we will effectively map scriptn to subs variabl;e sn.
After the PLSQL blocks completes the scriptn variables will have teh value 'noop.sql' or the name of teh script to run.
Then at the end, reference the subs variables in the '#' commands.
Anything with 'noop.sql' will execute a blank script.
I haven't used this myself but you might try something like this (simplified demo):
declare
vnum number := 0;
begin
--select count(tname) into vnum from tab where tname = 'DA_VERSION';
if vnum = 0 then -- include create script
execute immediate q'[
#callthis.sql
]';
end if;
end;
To work within execute immediate, the called script must contain a single statement and no semicolon.

My long time SQL*Plus loop doesn't print DBMS_OUTPUT.PUT_LINE output during execution

I know that in order to print something on sqlplus like below:
begin
dbms_output.put_line('Hello!');
end;
/
I need to call
set serveroutput on;
before that.
I also know that is not needed, but I can also call
DBMS_OUTPUT.enable;
before, just in case. This is working for me.
But what if I want to keep printing the progress of a long loop? It seems impossible to me. I've tried everything to print some progress on the loop below but just doesn't work. Is there some way of doing that? I even tried to spool to a file and didn't work.
Note 1: I can't truncate or partition this table as the DBA doesn't want to help me with that, so I have to use this nasty loop...
Note 2: I've noticed that once the loop is done, the whole output is printed. Looks like oracle is buffering the output and printing everything at the end. I'm not sure how to avoid that and print on every loop iteration.
set serveroutput on;
declare
e number;
i number;
nCount number;
f number;
begin
DBMS_OUTPUT.enable;
dbms_output.put_line('Hello!');
select count(*) into e from my_big_table where upd_dt < to_date(sysdate-64);
f :=trunc(e/10000)+1;
for i in 1..f
loop
delete from my_big_table where upd_dt < to_date(sysdate-64) and rownum<=10000;
commit;
DBMS_OUTPUT.PUT_LINE('Progress: ' || to_char(i) || ' out of ' || to_char(f));
end loop;
end;
Thank you for any answer.
There are 2 standard ways for such things:
set module and action in your session DBMS_APPLICATION_INFO.SET_MODULE:
SQL> exec DBMS_APPLICATION_INFO.SET_MODULE('my_long_process', '1 from 100');
PL/SQL procedure successfully completed.
SQL> select action from v$session where module='my_long_process';
ACTION
----------------------------------------------------------------
1 from 100
set session_longops:
DBMS_APPLICATION_INFO.SET_SESSION_LONGOPS
I'd recommend it in your case since that is exactly designed for long operations.
Example on Oracle-Base.
----
PS: dbms_output,put_line saves all output in a collection (nested table) variable of dbms_output package, so you can't get it from another session and client can't get it during user call (execution). In addition to set serveroutput on you can also get the output using dbms_output.get_lines: http://orasql.org/2017/12/10/sqlplus-tips-8-dbms_output-without-serveroutput-on/
Btw, in case if you need to filter or analyze output from dbms_output, sometimes it's convenient to get output in a query, so you can use filter strings in where clause or aggregate them: https://gist.github.com/xtender/aa12b537d3884f4ba82eb37db1c93c25
DBMS_OUTPUT will only ever be displayed after the PL/SQL code has terminated and control has returned to the calling program.
Output is, as you found, buffered. When your PL/SQL code finishes, then the calling program (e.g. SQL*Plus) can go and fetch that output.
Insert into another table, maybe call it "MYOUTPUT".
Create the table:
create table myoutput (lineno number, outline varchar2(80));
Add this after your delete:
insert into MYOUTPUT values (i,'Progress: ' || to_char(i) || ' out of ' || to_char(f));
Then select from MYOUTPUT periodically to see progress.
select outline from myoutput order by lineno;
Bobby
You can use UTL_FILE to write output to an external file, as in:
DECLARE
fh UTL_FILE.FILE_TYPE;
nRow_count NUMBER := 0;
BEGIN
fh := UTL_FILE.FOPEN('DIRECTORY_NAME', 'some_file.txt', 'w');
FOR aRow IN (SELECT *
FROM SOME_TABLE)
LOOP
nRow_count := nRow_count + 1;
IF nRow_count MOD 1000 = 0 THEN
UTL_FILE.PUT_LINE(fh, 'Processing row ' || nRow_count);
UTL_FILE.FFLUSH(fh);
END IF;
-- Do something useful with the data in aRow
END LOOP; -- aRow
UTL_FILE.FCLOSE_ALL; -- Close all open file handles, including
-- the ones I've forgotten about...
END;

PLSQL Passing Variables to External .SQL Scripts

I have 2 scripts, Script1.sql & Script2.sql. Script1.sql retrieves some data from a table in the database which I want to then pass to Script2.sql to use.
Script1.sql is as below:
SET SERVEROUTPUT ON;
DECLARE
FundRecord Test_Table%ROWTYPE;
CURSOR Fund_Cursor IS SELECT Code, YOURNAME FROM Test_Table;
BEGIN
OPEN Fund_Cursor;
LOOP
FETCH Fund_Cursor INTO FundRecord;
EXIT WHEN Fund_Cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Script1: ' || FundRecord.Code);
END LOOP;
CLOSE Fund_Cursor;
END;
/
#C:\Temp\Script2.sql FundRecord.Code;
And Script2.sql is as below:
BEGIN
DBMS_OUTPUT.PUT_LINE('Script 2:' || ' ' || '&1');
END;
/
The output from Script1.sql and Script2.sql is as follows:
Script1: ABDCE
Script2: FundRecord.Code
Why is the output of Script2 FundRecord.Code and not 'ABCDE' as I would expect?
How do I pass this in to ensure that Script2 is getting 'ABCDE' as the parameter?
Thanks
The record FundRrecord only exists within the PL/SQL block. You need to declare a separate variable that you can use outside the block:
set autoprint on serverout on
var somevalue varchar2(20)
col somevalue new_value somevalue
begin
for r in (
select dummy from dual
)
loop
dbms_output.put_line('Script 1: ' || r.dummy);
:somevalue := r.dummy;
end loop;
end;
/
#C:\Temp\Script2.sql &somevalue
The column ... new_value ... syntax is provided in SQL*Plus for page headers and footers in reports, but it is also very useful in scripts as it sets a define variable from the (last) result of a query. set autoprint on tells SQL*Plus to print the values of any bind variables (the ones with a leading :) after each PL/SQL block, and helpfully it does this by generating a query, allowing us to set up a column ... new_value and capture the result in a substitution variable.
Edit: regarding SQL Developer compatibility, I'll try some things out when I get a chance, but you might try adding something along the lines of
select :somevalue as somevalue from dual;
after the PL/SQL block, in case the column ... new_value construction works the same as in SQL*Plus but autoprint does not.
You can try as
#Script2.sql param1
and in Script2 SQL file, refer the parameter as
&1
Update 1
Here is my test case which works fine.
SELECT SYSDATE FROM &1;
This SQL statement is saved as Test.sql and it is invoked from SQLPLUS as
#D:\Test.sql dual
where dual is the parameter which been passed to Test.sql file
Result is displayed in the below screenshot

How do you pass an argument to a PL/SQL block within a sql file called using START in sqlplus?

I have a bash script running several sql files via sqlplus:
sqlplus $connectioninfo << end
start file1.sql
start file2.sql
start file3.sql $variable
quit
end
file3 has some PL/SQL:
BEGIN
DBMS_OUTPUT.PUT_LINE(&1);
END;
/
But it just prints the literal "&1" instead of the value of $variable. I have also tried the following in file3:
DEFINE var_a = &1;
BEGIN
DBMS_OUTPUT.PUT_LINE(var_a);
END;
/
and also the following:
DECLARE
var_b VARCHAR2(64) := &1;
BEGIN
DBMS_OUTPUT.PUT_LINE(var_b);
END;
/
and finally:
DEFINE var_a = &1;
DECLARE
var_b VARCHAR2(64) := var_a;
BEGIN
DBMS_OUTPUT.PUT_LINE(var_b);
END;
/
However, I am getting various errors or just the literal value '&1' for all of these.
Try adding SET DEFINE ON to the start of your script file3.sql.
If SET DEFINE is ON, SQL*Plus will replace &... substitution parameters with their values. If SET DEFINE is OFF (which it seems to be for you), SQL*Plus won't do this.

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