简体   繁体   English

如何将变量从Windows批处理文件传递到SQL * Plus

[英]How to pass a variable from a Windows Batch File to SQL*Plus

I want to pass a variable from a Windows Batch File to SQLPLUS, while displaying sql result batch variable should print along with the sql result. 我想将Windows批处理文件中的变量传递给SQLPLUS,同时显示sql结果,批处理变量应与sql结果一起打印。

Result should be stored in csv file. 结果应存储在csv文件中。

How can I do that. 我怎样才能做到这一点。

This is possible in Unix(shell script) how can I do that in Windows(batch script). 在Unix(shell脚本)中这是可能的,如何在Windows(批处理脚本)中做到这一点。

I want to pass a variable from a Windows Batch File to SQLPLUS 我想将变量从Windows批处理文件传递到SQLPLUS

Just pass it as an argument to the SQL script. 只需将其作为参数传递给SQL脚本即可。 And use substitution variables in the same order that of the arguments list &1 &2... 并以与参数列表&1 &2...相同的顺序使用替换变量&1 &2...

For example, 例如,

mybatchfile.BAT: mybatchfile.BAT:

sqlplus -S username/password@sid
@c:\sql\mysqlfile.sql 1000 7369

mysqlfile.SQL: mysqlfile.SQL:

update emp set sal = &1 where empno = &2

while displaying sql result batch variable should print along with the sql result. 在显示sql结果时,批处理变量应与sql结果一起打印。

To display the variables which you pass as arguments to the SQL script, first you need to define the bind variables, then assign the argument value and then print the value. 要显示作为参数传递给SQL脚本的变量,首先需要定义绑定变量,然后分配参数值,然后打印该值。

For example, 例如,

I have test.sql: 我有test.sql:

For NUMBER type 对于NUMBER类型

-- define the bind variable
var sal number

-- assign the first argument's value
exec :sal := &1

-- display the value
print :sal

-- define the bind variable
var empno number

-- assign the second argument's value
exec :empno := &2

-- display the value    
print :empno

Now, let's test the script: 现在,让我们测试一下脚本:

SQL> @D:\test.sql 1000 7369

PL/SQL procedure successfully completed.


       SAL
----------
      1000


PL/SQL procedure successfully completed.


     EMPNO
----------
      7369

SQL>

For STRING type 对于STRING类型

-- define the bind variable
var ename varchar2(10)

-- assign the argument's value
exec :ename := '&1'

-- display the value
print :ename

Now, let's test the script: 现在,让我们测试一下脚本:

SQL> @D:\test.sql LALIT

PL/SQL procedure successfully completed.


ENAME
--------------------------------
LALIT

SQL>

Result should be stored in csv file. 结果应存储在csv文件中。

Handle this in the SQL script. 在SQL脚本中进行处理。 Use proper SQL*Plus formatting for comma separated result. 对逗号分隔的结果使用正确的SQL * Plus格式。 To store the result set, you just need to SPOOL 要存储结果集,您只需要SPOOL

For example, 例如,

set colsep ,     -- separate columns with a comma
set pagesize 0   -- No headers
set trimspool on -- remove trailing blanks

spool mycsvfile.csv

SELECT ....

spool off

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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