Pl/Sql Variable Assignment In Shell



Oracle Concepts - Displaying PL/SQL Output

Oracle Tips by Burleson Consulting

Displaying PL/SQL Output

Another change with PL/SQL from SQL is that the database does not return the output.  PL/SQL code normally will change data, insert values, and so forth, inside the database.  It will not normally display results back to the user.  To do this we use a procedure called dbms_output.put_line to place the results in a buffer that SQL*Plus will retrieve and display.  SQL*Plus must be told to retrieve data from this buffer in order to display the results.  The SQL*Plus command 'set serveroutput on' causes SQL*Plus to retrieve and display the buffer.

SQL> declare  2    v_line varchar2(40);  3  begin  4    v_line := 'Hello World';  5    dbms_output.put_line (v_line);  6  end;  7  / PL/SQL procedure successfully completed. SQL> set serveroutput onSQL> declare  2    v_line varchar2(40);  3  begin  4    v_line := 'Hello World';  5    dbms_output.put_line (v_line);  6  end;  7  /Hello World PL/SQL procedure successfully completed.

The first time the script is run, the result was just a notice that the script completed successfully.  Once we set serverouput on and rerun the script, the results are shown. 

As discussed earlier, this is an anonymous block of PL/SQL code.  It is sent to the database, compiled and executed, then SQL*Plus retrieves the results.  The script is stored in the SQL*Plus buffer and can be rerun by executing the forward slash.

SQL> /Hello World PL/SQL procedure successfully completed.

The script is not stored in the database (like a stored or named procedure).   It must be resent to the database and compiled each time it is executed.

For the complete story, we recommend the book 'Easy Oracle PL/SQL Programming'.  Once you have mastered basic SQL you are ready for the advanced book 'Oracle PL/SQL Tuning' by Dr. Timothy Hall.

As with SQL statements, SQL*Plus variables can be used to make the PL/SQL script dynamic.  Just as with a SQL statement, the variables are local to SQL*Plus and are substituted before the code is sent to the database.

SQL> declare  2    v_line varchar2(40);  3  begin  4    v_line := 'Hello &name';  5    dbms_output.put_line (v_line);  6  end;  7  /Enter value for name: Johnold   4:   v_line := 'Hello &name';new   4:   v_line := 'Hello John';Hello John

The SQL*Plus accept command is a more flexible method of embedding dynamic data in the script.

SQL> accept v_string prompt "Enter Your First Name: " Enter Your First Name: Thomas SQL> declare  2    v_line varchar2(40):= '&v_string';  3  begin  4    v_line := 'Hello '||v_line;  5    dbms_output.put_line (v_line);  6  end;  7  / old   2:   v_line varchar2(40):= '&v_string';new   2:   v_line varchar2(40):= 'Thomas'; Hello Thomas PL/SQL procedure successfully completed.


Let's look at this script a little closer.  The first line is the SQL*Plus accept command to get the SQL*Plus variable v_string.  This line must be executed alone, not part of the PL/SQL block.  At the prompt the name Thomas was entered.  Now the script is run but it is slightly modified from previous examples.

SQL> declare  2    v_line varchar2(40):= '&v_string';

The variable v_line is declared as a varchar2(40) and is given a default value that equals v_string.  The PL/SQL assignment operator (:=) is used to assign the value.  Hence, v_line is a bucket that gets assigned the string 'Thomas'.  A developer would read an assignment statement in English as 'v_line gets v_string' to indicate the assignment.  Let's examine a more complex assignment statement.

4    v_line := 'Hello '||v_line;

Line 4 uses the concatenate operator to append 'Hello ' to the front of v_line and then assigns it back to the variable v_line.  The variable v_line now contains the string 'Hello Thomas'.  Line 5 places the value of v_line in the buffer to be retrieved by SQL*Plus.

old   2:   v_line varchar2(40):= '&v_string';new   2:   v_line varchar2(40):= 'Thomas';

These two lines demonstrate SQL*Plus's verify function showing us what is substituted before the code is sent to the database for execution.  This information can be switched on/off with the verify command

SQL> set verify onSQL> set verify off

PL/SQL Variable Declaration and Conversion

In the previous examples a variable v_line was defined.  All variables are defined in the declaration section of the block.  Variables are defined in the form:

variableName      datatype    := defaultvalue;

Below are examples of variables.  Variables can be defined as any valid datatype to include user defined datatypes and records.

declare  v_str1    varchar2(80);  v_str2    varchar2(30) := 'Hello World';  d_today   date;  n_sales   number;  n_order   number(8);begin

A constant is defined the same way a variable is with the key word constant.

c_standard constant number := 90;

Notice that a constant must be assigned a value and the above statement does four things:

* Names the variable c_standard

* Defines c_standard as a constant

* Defines c_standard as a numeric datatype

* Assigns a value of 90 to c_standard

With PL/SQL constants, note that a constant value can't be changed unless it is redefined in a subsequent block. 

In the examples above our two variables are defined as numbers, and we are now ready to see how to include the precision and scale for a number.  As in SQL, PL/SQL supports mathematical operations and has a large library of mathematical functions, covering everything from advanced multivariate statistics to Newtonian Calculus.  PL/SQL also supports single-row functions to convert numbers to characters and characters to numbers.

This is an excerpt from the bestselling "Easy Oracle Jumpstart" by Robert Freeman and Steve Karam (Oracle ACE and Oracle Certified Master).  It's only $19.95 when you buy it directly from the publisher here.

If you like Oracle tuning, you may enjoy the new book "Oracle Tuning: The Definitive Reference", over 900 pages of BC's favorite tuning tips & scripts. 

You can buy it direct from the publisher for 30%-off and get instant access to the code depot of Oracle tuning scripts.


Question:  Within SQL*Plus is there a way to get this value into a shell script environment variable?

How do I pass a variable to SQL*Plus in a ksh shell script?

Answer:  Passing variables to shell scripts is tricky!  Jon Emmons as a great book "Oracle Shell Scripting" with lots of working examples of passing user defined variables to Oracle in a shell script.  Working scripts exist in the books code download.

Also see passing variables to SQL*Plus.

 I used numbered variables, like &1 and &2, but as long as they are defined and exported in the shell script, they will be resolved in SQL*Plus (unless they contain special characters).  

In cases where a variable contains special characters ($owner), you have to "escape" variables in sqlplus when they contain dollar signs . . .

 If you do it all one line (a requirement in Windows shell scripting), it's easy to pass a ksh shell script variable into sqlplus:

export $min_snap

export $max_snap

$ORACLE_HOME/bin/sqlplus -S perfstat/perf$ORACLE_SID@$ORACLE_SID @sppurge $min_snap $max_snap

Here are some working examples using the C shell:

sqlplus -S system/manager << EOF
SELECT username, account_status, expiry_date
FROM dba_users WHERE lower(username)=lower('$lookup');

Shell Variables and Embedded SQL

Earlier in this chapter, we saw how SQL can be embedded in a shell script.  One side benefit to this method is that we can use shell variables to represent values within the embedded SQL.  In the following script we pass a username to the script as an argument, it is transferred to a variable named lookup for better readability and the variable lookup is used in the WHERE clause within the SQL.

sqlplus -S system/manager << EOF
SELECT username, account_status, expiry_date
FROM dba_users WHERE lower(username)=lower('$lookup');

The result is a single script which can take an argument and execute SQL using the value of that argument.  This can be a very efficient way to load data into Oracle tables without the need for a load file or other intermediate step.

Here is another example where the entire SQL*Plus session is passed as a single variable called invalid_count:

invalid_count=`sqlplus -L -s / as sysdba <<.eof.  
set pages 0 feed off heading off echo off verify off termout off  
select count(*) from dba_objects where status != 'VALID';  
echo $invalid_count

In the code above, note that the shell script accepts the SQL*Plus output via the use of the "grave (`)" symbol.

Again, for complete examples of passing complex variable to SQL*Plus from  a shell script, get the code download in "Oracle Shell Scripting".


Leave a Reply

Your email address will not be published. Required fields are marked *