简体   繁体   中英

How to set default value for missing substitution parameter

I'm calling a procedure in a script and passing variables like this:

@@./procedudure.sql 'var1' 'var2' 'var3'

In the procedure I'm using the values like this:

DEFINE variable1 = '&1'
DEFINE variable2 = '&2'
DEFINE variable3 = '&3'
...
insert into TABLE (id, text) values ('&varibale1', '&variable2&variable3')

I want to be able to call the procedure with only two parameters instead of 3 so that the last one is replaced with empty string. But when I call it like this, I get this prompt:

Enter value for 3: 

I've also tried to use the parameters like this, but with the same result:

DEFINE variable2 = '&2' || '&3'

I've found this page for using prompt for missing variable, but couldn't find anywhere how to set a default value: https://blogs.oracle.com/opal/entry/sqlplus_101_substitution_varia#9_14

As you can see from the code, I want the last parameters to be concatenated. This should be a workaround for 240-character limit.

Well yes I see it's old but... until now, unanswered!

OP, this is what you're looking for but it's not exactly simple. I originally spotted the technique on Tanel Poder's website but not sure if he came up with it or not.

Anyway, here I'm using it to setup defaults in case warning and critical limits are not passed in to the script.

rem setup default values
def DEFAULT_WARN_LEVEL='97'
def DEFAULT_CRIT_LEVEL='99'

rem trick to assign values to &1 and &2 so that SQL*Plus does not ask
col warn_level new_value 1
col crit_level new_value 2
select null warn_level
,      null crit_level
from   dual
where  1=2
/

rem if values were passed in, use them, if not, use the defaults
select nvl('&1','&DEFAULT_WARN_LEVEL') warn_level
,      nvl('&2','&DEFAULT_CRIT_LEVEL') crit_level
from   dual
/
rem the values, either passed in or defaults are now in &1 and &2

rem put the values in meaningful variables
def warn_level='&1'
def crit_level='&2'

When you code it as DEFINE variable3 = '&3' in your procedure, the system thinks 3 is variable and it will always prompt for its value.

In case you want to pass a default value for 3, you should do DEFINE 3 = YOUR_VALUE_FOR_PARAM_3

In the example link, section 9.14, I don't see where he uses any default value. He just either asks for it, or takes the parameter. SQLPLUS always is going to ask for any &1, &2, .. he sees in your file, if it is not given as input parameter. No matter how and where you use it. It's not like in Bash, where he just replaces $1 with null, and doesn't do anything. I don't think you can disable the auto-asking in SQLPLUS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM