【问题标题】:Passing the name of spool file to sqlplus from a shell script将假脱机文件的名称从 shell 脚本传递给 sqlplus
【发布时间】:2017-02-01 07:38:15
【问题描述】:

我正在尝试编写一个 unix 程序,在该程序中我需要连接到 SQL DB 并获取数据并将其存储到文件中。

目前我正在使用以下命令:

output1=`sqlplus -s username@SID/password <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF;
SPOOL EMP_NAMES.txt
select emp_name from employee order by emp_name;
Spool off;

这工作正常。但我的要求是我想传递 spool 文件的值,这样每次都会生成一个新的 Spool 文件。

我基本上想在文件名末尾附加日期,例如:

date=`date +'%d/%m/%Y_%H:%M:%S:%2N'`
output1=`sqlplus -s username@SID/password <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF;
SPOOL EMP_NAMES_$date.txt

请告诉我如何做到这一点。

【问题讨论】:

    标签: linux oracle bash shell unix


    【解决方案1】:

    如果您使用heredoc 致电您的sqlplus,您可以轻松做到这一点:

    spool_file=: ... your date logic here ...
    sql_ouput=: ... path for sqlplus output & errors ...
    sqlplus -s username@SID/password << EOF &> "$sql_output"
      SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF;
      spool $spool_file
      # SQL statements
      spool off
    EOF
    if [[ $? != 0 ]]; then
      : ... error handling ...
    fi
    
    • 最好将sqlplus 的stdout/stderr 捕获到文件中而不是shell 变量中。
    • 我认为可以通过从命令行中删除密码并将其添加为heredoc的第一行来隐藏密码(这将防止密码在ps中显示)

    看看这个相关的帖子:Connect to sqlplus in a shell script and run SQL scripts

    【讨论】:

    • 感谢@codeforester 的超快速响应!!!我已经尝试了建议的步骤,但仍然出现错误。 spoolFile="SPOOL_FILE_"$date".txt" output1=`sqlplus -s username@SID/pwd
    • "EOF" 是否位于行首并且该行没有其他字符?您遇到什么错误?
    • 它在行尾就像 -- output1=`sqlplus -s username@SID/pwd
    • 谢谢@codeforester !!!有效。我只是以您提到的类似方式重新编写了代码并且它起作用了。非常感谢!!!
    猜你喜欢
    • 2017-02-14
    • 1970-01-01
    • 2013-07-08
    • 2020-12-06
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    相关资源
    最近更新 更多