嵌套的sql脚本和变量

时间:2014-09-03 20:59:18

标签: sql oracle

当我有一个我将参数传递给的嵌套脚本时,如何避免覆盖命令行参数。

例如:

我运行命令sqlplus user / pass @ test_include.sql 1 2 3.哪个应该打印值1,2和3.

test_include.sql包含一个嵌套的sql脚本,我传递了参数x和y。

问题是,& 1,& 2应该是1和2正被替换为下标中的x和y。

这是test_include.sql代码:

set verify off
set echo on


@ nested_sql_script.sql x y

select
  '&_example_date_' as example_date
from
  dual
;

select '&&1' parm1 from dual;
select '&&2' parm2 from dual;
select '&&3' parm3 from dual;


exit

以下是nested_sql_script.sql的代码:

define _example_date_ = ''


-- store the resulting value in a "replacement" variable named &_CIM_TABLESPACE_NAME_
column my_val new_value _example_date_

select '&1' as x, '&2' as y, to_char(sysdate, 'mm/dd/yyyy hh24:mi:ss') as my_val from dual;

select
   '&_example_date_' as nested_sql_example_date
from dual
;

这是输出:

**sqlplus user/pass @test_include.sql 1 2 3**

 SQL*Plus: Release 11.2.0.3.0 Production on Wed Sep 3 15:32:53 2014

 Copyright (c) 1982, 2011, Oracle.  All rights reserved.


 Connected to: Oracle Database 11g Enterprise Edition Release
 11.2.0.3.0 - 64bit Production With the Partitioning, Automatic Storage Management, OLAP, Data Mining and Real Application Testing options

 SQL> 
 SQL> 
 SQL> @ nested_sql_script.sql x y SQL> define _example_date_ = '' 
 SQL> 
 SQL> 
 SQL> column my_val new_value _example_date_ 
 SQL> 
 SQL> select '&1' as x, '&2' as y, to_char(sysdate, 'mm/dd/yyyy hh24:mi:ss') as my_val from dual;

 X Y MY_VAL 
 -------------------
 x y 09/03/2014 15:32:53

 SQL> SQL> select   
 2     '&_example_date_' as nested_sql_example_date
 3  from dual   
 4  ;

 NESTED_SQL_EXAMPLE_DATE
 -------------------
 09/03/2014 15:32:53

 SQL> SQL> SQL> select   
 2    '&_example_date_' as example_date  
 3  from   
 4    dual   
 5  ;

 EXAMPLE_DATE 09/03/2014 15:32:53

 SQL> SQL> select '&&1' parm1 from dual;

 P
 -
 x

 SQL> select '&&2' parm2 from dual;

 P
 -
 y

 SQL> select '&&3' parm3 from dual;

 P
 -
 3

 SQL> SQL> SQL> exit Disconnected from Oracle Database 11g Enterprise
 Edition Release 11.2.0.3.0 - 64bit Production With the Partitioning,
 Automatic Storage Management, OLAP, Data Mining and Real Application
 Testing options

1 个答案:

答案 0 :(得分:3)

您无法阻止更换位置参数; it's a (lack of) scoping issue, really。所有你真正能做的就是在包含嵌套脚本之前将值存储为命名参数,这是凌乱的:

define orig1=&1
define orig2=&2
define orig3=&3

@nested_sql_script.sql x y

select '&orig1' parm1, '&orig2' parm2, '&orig3' parm3 from dual;

您可以将它们分配给绑定变量,但它基本上是相同的。