I was making a generic SQL script. To make it generic, I decided to use command line arguments to the script.
To do this, I created a defined variable that is set to the 1st parameter (&1
). Then, throughout the script, I can use
&ACCT_NBR
, instead of hard coding the value.
DEFINE ACCT_NBR=’&1′
SELECT * from account WHERE acct_nbr = &ACCT_NBR.
This worked fine. You just have to SET DEFINE ON
before using & in your script.
(Of course, the actual script has multiple SQLs using this variable. I just included a simple one above to show the usage.)
But then, I was worried about future users of the script forgot to add command line argument. The whole script may go crazy. I wanted to have sort of an IF check and exit before any other script was executed, in case the parameter was missing. But, plain SQL does not offer this in Oracle. (PL/SQL does, but that’s a whole different language with it’s own quirks! For my task, PL/SQL might have been an overkill).
After trying several things, I came up with the below lines:
WHENEVER SQLERROR EXIT SQL.SQLCODE
DEFINE ACCT_NBR=’&1′
SELECT &ACCT_NBR FROM dual;
This prompts for the value of (parameter) 1, if the parameter was missing from command line.
12:07:13 SQL> DEFINE ACCT_NBR=’&1′
Enter value for 1:
Here I pressed enter, thus the parameter is not set. It errors out with the below message:
12:07:13 SQL> SELECT &ACCT_NBR FROM dual;
old 1: SELECT &ACCT_NBR FROM dual
new 1: SELECT FROM dual
SELECT FROM dual
*
ERROR at line 1:
ORA-00936: missing expression
and the script exits.
So, there you have it. an IF
check without the IF
in SQL!
Originally a Physics major, fell in love with Microprocessors and switched to Computer Science 20+ years ago. Since then, dabbled in various languages including, PowerBuilder, Oracle, Java, C, C++, Perl, Python etc. Constantly striving for quality and performance too.
I try to help fellow developers with technology as a way of "giving back to the community". Blogging became a natural extension of that effort. Still learning to perfect that art. If one new programmer out there benefits from this blog, my time and effort are fully worth it.
The underlying theme in my blogs is power and beauty of programming (and technology in general). A well written program gives me the sense of awe you get when you look at a man made wonder like Angkor Wat. You experience poetry, art, mystique, power all at once. A program and the troubleshooting that ensues also gives you a feeling you get while reading a mystery novel!