Skip to Main Content
  • Questions
  • How can I get variable value from anonymous block to shell script

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question.

Asked: April 28, 2016 - 9:42 pm UTC

Last updated: April 29, 2016 - 4:37 pm UTC

Version: 11.1.0

Viewed 1000+ times

You Asked

Good Day, Tom..!!
As per my requirement written the code to get last record date from first 100 records(bulk collect limit clause to 100) and from collection variable assigned the output date to variable; and I want this variable value to be echoed in shell variable.

Please suggest. ..nothing is echoing in shell..I tried with exec dbms_output.put_line(), can't fetch value however I can display some msg with it like "Hello World".

Appreciate your patience :-)

#!/bin/bash
batch_size=100
db_str=${uname}/${psd}@${dbname}
v_end_id=$(sqlplus -s ${db_str} <<-EOS
DECLARE
cursor ajc_cur is
SELECT created_date
FROM ****
WHERE rownum < = 1000
ORDER BY created desc;
TYPE rec_tb IS TABLE OF ***.created_date%TYPE;
l_created_dates rec_tb;
v_created date;
BEGIN
OPEN ajc_cur;
LOOP
FETCH ajc_cur bulk collect into into l_created_dates limit '$v_batch_size';
EXIT WHEN ajc_cur%NOTFOUND;
v_created := l_created_dates('$v_batch_size');
dbms_output.put_line(v_created);
END LOOP;
CLOSE ajc_cur;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('Data error..');
END;
/
exit;
EOS
)
echo $v_end_id

and Chris said...

To ensure the output from your dbms_output calls are shown, enable serveroutput in SQL*Plus:

...
v_end_id=$(sqlplus -s ${db_str} <<-EOS
set serveroutput on
DECLARE
...


A few other points:

- There's no need for quotes around $v_batch_size in the PL/SQL block
- Also, this variable isn't set! The one that is is batch_size
- The script will fetch all rows from the query. If you just wan the first of these, batch, remove the loop.
- If the query returns less than batch_size rows, this will return nothing!

If you always want to see the last row, replace:

v_created := l_created_dates($v_batch_size);

with:

v_created := l_created_dates(l_created_dates.last);

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Returning collection value from anonymous block to shell variable

Hima, April 29, 2016 - 4:27 pm UTC

Thank you for your great help and few additional suggestions. It works :-) :D.. You made my work easy and you made my day and weekend too :-)
Connor McDonald
April 29, 2016 - 4:37 pm UTC

Happy to help.

More to Explore

DBMS_OUTPUT

More on PL/SQL routine DBMS_OUTPUT here