Default value for paramteters not passed SQLPlus script

百般思念 提交于 2019-12-03 16:36:29

问题


Is there a way to set default value of paramter in sqlplus script without user input?

For example, I have an SQL script sessions.sql:

SET VERIFY OFF
SET TERMOUT OFF
DEFINE uname = '&1'

COLUMN search_uname new_value search_uname
SELECT CASE WHEN '&uname' = '' THEN '%' ELSE UPPER('&uname') END AS search_uname 
FROM dual;

SET TERMOUT ON

SELECT sid, serial, username FROM v$session WHERE username LIKE '&search_uname';

And I want to invoke it from sqlplus like this:

SQL> @sessions
Enter value for 1:

       SID    SERIAL# USERNAME
---------- ---------- ------------------------------
    56  20577 CONTEXT
.....
236 rows selected.

SQL> @sessions ""

       SID    SERIAL# USERNAME
---------- ---------- ------------------------------
    56  20577 CONTEXT
.....
236 rows selected.

SQL> @sessions SDE

       SID    SERIAL# USERNAME
---------- ---------- ------------------------------
       113  56675 SDE
       165  64881 SDE
.....
43 rows selected.

SQL> 

I can only pass an empty value for parameter when I am asked to enter it, or I am able to pass an empty parameter after script name through "". But this behaviour is very annoying. Some kind of IF DEFINED "&1" will be very usefull.

Do you have any tips or tricks how this should be achieved to apply WHERE conditions in sqlplus script wheter parameter is defined or not without unnecessary user interaction?

Solution

According to the article linked by Martin I modified previous script to be working without aksing for parameter values:

SET VERIFY OFF
SET TERMOUT OFF

column 1 new_value 1
SELECT '' "1" FROM dual WHERE ROWNUM = 0;
define uname = '&1'

SET TERMOUT ON

SELECT sid, serial#, username FROM v$session 
WHERE username LIKE UPPER(DECODE('&uname', '', '%', '&uname'));

undefine 1

回答1:


Please read "On SQL*Plus Defines" for an answer to your question.




回答2:


For those who don't fancy chasing and perusing links that can go away anytime, here's a quick cut'n paste snippet.

set termout on
set serveroutput on
set feedback off
set verify off

-- start
column 1 new_value 1 noprint
select '' "1" from dual where rownum = 0;
define param = &1 "default"
-- end

begin
    dbms_output.put_line ( 'Param 1 value is &param' );
end;
/

exit 0
/

Execution:

$ sqlplus -s SCOTT/TIGER@ORCL @a.sql
Param 1 value is default
$ sqlplus -s POSF/POSF@ECMDB @a.sql nondef
Param 1 value is nondef



来源:https://stackoverflow.com/questions/13474899/default-value-for-paramteters-not-passed-sqlplus-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!