【问题标题】:How to pass a variable from a Windows Batch File to SQL*Plus如何将变量从 Windows 批处理文件传递到 SQL*Plus
【发布时间】:2015-06-06 23:05:43
【问题描述】:

我想将一个变量从 Windows 批处理文件传递给 SQLPLUS, 在显示 sql 结果时,批处理变量应与 sql 结果一起打印。

结果应该存储在 csv 文件中。

我该怎么做。

这在 Unix(shell 脚本)中是可能的,我如何在 Windows(批处理脚本)中做到这一点。

【问题讨论】:

  • 只需将其作为参数传递给 SQL 脚本并使用substitution variables。并将结果集存储为 CSV 文件,使用SPOOL 并格式化为set colsep ,

标签: windows oracle batch-file oracle11g sqlplus


【解决方案1】:

我想将一个变量从 Windows 批处理文件传递给 SQLPLUS

只需将它作为参数传递给 SQL 脚本。并以与参数列表相同的顺序使用替换变量&1 &2...

例如,

mybatchfile.BAT:

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

mysqlfile.SQL:

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

在显示 sql 结果时,批处理变量应与 sql 结果一起打印。

要显示作为参数传递给 SQL 脚本的变量,首先需要定义绑定变量,然后分配参数值,然后打印该值。

例如,

我有 test.sql:

对于 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

现在,让我们测试一下脚本:

SQL> @D:\test.sql 1000 7369

PL/SQL procedure successfully completed.


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


PL/SQL procedure successfully completed.


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

SQL>

对于STRING类型

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

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

-- display the value
print :ename

现在,让我们测试一下脚本:

SQL> @D:\test.sql LALIT

PL/SQL procedure successfully completed.


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

SQL>

结果应该存储在 csv 文件中。

在 SQL 脚本中处理这个问题。对逗号分隔的结果使用正确的 SQL*Plus 格式。存储结果集只需SPOOL

例如,

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

spool mycsvfile.csv

SELECT ....

spool off

【讨论】:

  • 我不想在查询中使用它们,我只想显示该变量。比如说变量是我想在sql输出中显示的字符串。
  • 查看更新后的答案。我添加了一个如何显示参数值的示例。请将其标记为已回答,也会对其他人有所帮助。
  • 你能解释一下如何将字符定义为绑定变量吗?
  • 好的,我已经分别添加了数字类型和字符串类型的示例。请参阅我的更新答案。
  • 它不适用于字符,它给出的错误必须声明 PLS 0021 标识符。
猜你喜欢
  • 1970-01-01
  • 2021-11-08
  • 2015-05-12
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多