SQL, pl/sql, sqlplus: how to return a variable to DOS batch file

batchbatch-fileoracleplsqlsql

I have a DOS batch file which invokes sqlplus, which executes some basic SQL contained in another .sql file, and I want the last part of it to return a value back to the dos batch file. However, while there are many examples via Google on how to do this using a Unix shell, the closest I get for DOS batch files is something like this:

SELECT
  MAX(magicnumber)
INTO
  :ret_val
FROM
  ABCD.EFGH

exit :ret_val

However, this does not work for me – sqlplus just gives me a usage message for EXIT.

If I do "exit 15", for instance, the DOS batch file correctly reports the return code (using errorlevel), so that part is okay.

Is there some syntax thing I am missing out on? I should note that I am very new to SQL stuff so it might be some very obvious thing I'm not seeing… Thanks!

Best Answer

A sort-of workaround is to simply have it print out the result, and then capture that output the way the unix shells do. User "shoblock" on dbforums.com provides this example here:

http://www.dbforums.com/oracle/1034420-how-return-value-pl-sql-script.html

In essence, the bat file has:

FOR /F "usebackq delims=!" %%i IN (`sqlplus -s u/p@db @t`) DO set xresult=%%i
echo %xresult%

For now I'm going with this.