Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Contents of File as Parameter to Sql*Plus Command

Tags:

oracle

sqlplus

I'm trying to write a sqlplus command that creates a table from a query that is stored in an .sql file.

The particular .sql file that contains the query would be supplied to my sqlplus command as a variable (&v_InputQuery).

I've tried something like this, but it doesn't work.

CREATE TABLE &v_OutputTable AS
(
< &v_InputQuery
)
;

I get an error saying that there's a missing SELECT keyword.

What I'd really like is for &v_InputQuery to be replaced not with the name of the file specified by the user, but with the actual contents of the file. Is there a way to do that?

Thank you very much.

like image 579
Steve Avatar asked Dec 30 '13 23:12

Steve


People also ask

Which command is used to execute a SQL file in SQL*Plus environment?

SQL Command Line (SQL*Plus) is a command-line tool for accessing Oracle Database XE. It enables you to enter and run SQL, PL/SQL, and SQL*Plus commands and statements to: Query, insert, and update data. Execute PL/SQL procedures.

Which is an iSQL * Plus command in SQL?

SQL*Plus is a command-line tool that provides access to the Oracle RDBMS. SQL*Plus enables you to: Enter SQL*Plus commands to configure the SQL*Plus environment. Startup and shutdown an Oracle database.


2 Answers

Yes, you can do that. If your query is in a file called v_InputQuery.sql, you can do this:

CREATE TABLE &v_OutputTable AS (
@v_InputQuery.sql
) ;

It's important that the @ is the first character on the line. SQL*Plus will read the file and put its contents at that location. So make sure you don't have any terminating characters in the file such as ; or /.

like image 127
Jeffrey Kemp Avatar answered Sep 20 '22 21:09

Jeffrey Kemp


Unfortunately, You cannot create a SQL*Plus command, but instead create a shell script to do it!

Lets say my_script.sh is below

#you can always complete the user interaction at unix/dos
USER=your_user
PASS=your_pass
DB=your_db
OUTPUT_TABLE=$1;
QUERY_FILE=$2;
SELECT_QUERY=`cat $QUERY_FILE`;

sqlplus -S ${USER}/${PASS}@${DB} << !
SET SERVEROUTPUT ON;
VAR EXITCODE NUMBER;

BEGIN
   EXECUTE IMMEDIATE ' CREATE TABLE $OUTPUT_TABLE AS $SELECT_QUERY ';
   :EXITCODE := SQLCODE;
EXCEPTION
WHEN OTHERS THEN
   DBMS_OUTPUT.PUT_LINE(SQLERRM);
   :EXITCODE := SQLCODE;
END;
/

exit :EXITCODE
!

Executing the script as below(Depends on OS)

ksh my_script MY_OUTPUT_TABLE my_sql.sql;
like image 34
Maheswaran Ravisankar Avatar answered Sep 17 '22 21:09

Maheswaran Ravisankar