如何在shell脚本中运行SQL

Gab*_*e M 4 sql unix oracle shell

如何在设置变量时在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
Run Code Online (Sandbox Code Playgroud)

Gab*_*e M 6

#!/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"
Run Code Online (Sandbox Code Playgroud)

  • @Aneri,不确定你以前是否使用过SO,但是写一个问题并添加SO中不存在的答案正在为SO增加价值.它实际上是一个功能. (13认同)

Bri*_*new 5

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

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

因此sqlplus将消耗掉所有多达EOFstdin 的标记。