Linux/Unix shell sql 之间传递变量

灵活结合Linux/Unix Shell 与SQL 之间的变量传输,极大程度的提高了DBA的工作效率,本文针对Linux/Unix shell sql 之间传递变量给出几个简单的示例以供参考。

一、示例

1、shell变量接受sql返回值之方式一
Oracle@SZDB:~> more ./retval.sh
#!/bin/bash
RETVAL=`sqlplus -silent scott/tiger <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
SELECT * FROM emp WHERE ename='SCOTT';
EXIT;
EOF`
if [ -z "$RETVAL" ]; then
  echo "No rows returned from database"
  exit 0
else
  echo $RETVAL
fi

oracle@SZDB:~> chmod u+x retval.sh
oracle@SZDB:~> ./retval.sh
7788 SCOTT ANALYST 7566 19-APR-87 34171.88 20

2、shell变量接受sql返回值之方式二
oracle@SZDB:~> more ./retval_2.sh
#!/bin/bash
sqlplus -S "scott/tiger" <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
col cnt new_value v_cnt
SELECT count(*) cnt FROM emp WHERE deptno=10;
exit v_cnt
EOF
VALUE="$?"
echo "show rows for deptno 10:$VALUE"

3、将shell变量作为参数传递给sql脚本
oracle@SZDB:~> more ./retval_3.sh
#!/bin/bash
v_empno="$1"
sqlplus -S "scott/tiger" <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
SELECT ename FROM emp WHERE empno=$v_empno;
exit
EOF
exit

oracle@SZDB:~> ./retval_3.sh 7788
SCOTT

相关推荐