如何在shell脚本中运行SQL

时间:2013-10-04 13:21:05

标签: sql oracle shell unix

如何在设置变量时在shell脚本中运行SQL命令?我曾尝试过这种方法并且没有执行命令,它认为命令只是一个字符串。

#!/bin/ksh
variable1=`sqlplus -s username/pw@oracle_instance <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
select count(*) from table;
EXIT;
EOF`
if [ -z "$variable1" ]; then
  echo "No rows returned from database"
  exit 0
else
  echo $variable1
fi

5 个答案:

答案 0 :(得分:5)

#!/bin/ksh
variable1=$( 
echo "set feed off
set pages 0
select count(*) from table;
exit
"  | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"

答案 1 :(得分:4)

您可以使用heredoc。例如从提示:

$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF

所以sqlplus将消耗EOF标记之前的所有内容作为标准输入。

答案 2 :(得分:0)

回答可能为时已晚,但有一个正常的代码:

sqlplus -s "/ as sysdba" << EOF
    SET HEADING OFF
    SET FEEDBACK OFF
    SET LINESIZE 3800
    SET TRIMSPOOL ON
    SET TERMOUT OFF
    SET SPACE 0
    SET PAGESIZE 0
    select (select instance_name from v\$instance) as DB_NAME,
           file_name
      from dba_data_files
     order by 2;

答案 3 :(得分:0)

sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;

connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;

truncate table tmp;

exit;
EOF

答案 4 :(得分:0)

<强>代码

PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"

OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
           select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";

<强>解释

PL_CONNECT_STRING携带数据库用户名,密码及其服务名称

sqlplus用于将数据库与PL_CONNECT_STRING详细信息

连接

END-OF-SQL标记包含您要执行的查询

echo用于打印查询的输出

注意:您可以在END-OF-SQL标记内提供多个查询,因此它对批处理执行也很有用