sqlplus與shell互相傳值的幾種情況
情況一:在shell中最簡單的調用sqlplus
$cat test.sh
#!/bin/sh
sqlplus oracle/oracle@oracle>file.log <<EOF
select * from test;
exit
EOF #注意EOF要頂格寫
$sh test.sh
$cat file.log
--省略若干系統提示信息-------
SQL>
EMPNO EMPNAME SAL DEPTNO
----- ------------- ----- ------
10002 Frank Naude 500 20
10001 Scott Tiger 1000 40
--省略若干系統提示信息-------
將執行過程重定向入文件file.log,可通過cat file.log查看
情況二:直接將sqlplus的值賦值給shell變量
$cat test.sh
#!/bin/sh
# 將sqlplus的結果輸出給變量VALUE
# set命令的使用可查詢手冊
#注意shell中等號兩邊不能有空格
VALUE=`sqlplus -S /nolog <<EOF
set heading off feedback off pagesize 0 verify off echo off
conn oracle/oracle@oracle
select count(*) from test;
exit
EOF`
#輸出記錄數
echo "The number of rows is $VALUE."
$sh test.sh
The number of rows is 2.
顯示結果正確,表test共2條記錄
情況三:間接將sqlplus的值賦值給shell變量
$cat test.sh
#!/bin/sh
#利用COL column NEW_VALUE variable定義變量
#sqlplus執行完后最后返回值為v_coun
#利用$?將最后返回值賦值給VALUE,也即為test的記錄數
sqlplus -S /nolog <<EOF
set heading off feedback off pagesize 0 verify off echo off
conn oracle/oracle@oracle
col coun new_value v_coun
select count(*) coun from test;
exit v_coun
EOF
VALUE="$?"
echo "The number of rows is $VALUE."
$sh test.sh
2
The number of rows is 2.
腳本執行結果中第一個2為sqlplus返回值,第二個2為VALUE的值
情況四:將shell變量的值傳給sqlplus使用
$cat test.sh
#!/bin/sh
#sqlplus引用shell變量TABLENAME的值
#注意賦值時,等號兩邊不能有空格
TABLENAME="test"
sqlplus -S oracle/oracle@oracle <<EOF
select * from ${TABLENAME};
exit
$sh test.sh
EMPNO EMPNAME SAL DEPTNO
----- -------------------------------------------------- ---------- ------
10002 Frank Naude 500 20
10001 Scott Tiger 1000 40
腳本執行結果為:select * from test;的結果
情況五:通過交互方式手工輸入shell變量值
$cat test.sh
#!/bin/sh
#將手工輸入變量值讀入變量TABLENAME
echo "Enter the tablename you want to select:"
read TABLENAME
sqlplus -S oracle/oracle@oracle <<EOF
select * from ${TABLENAME};
exit
$sh test.sh
#按提示輸入表名test
Enter the tablename you want to select:
test
EMPNO EMPNAME SAL DEPTNO
----- -------------------------------------------------- ---------- ------
10002 Frank Naude 500 20
10001 Scott Tiger 1000 40
腳本執行結果為select * from test的執行結果
情況六:通過重定向文件方式,並生成日志
source ~/.bash_profile
sqlplus test/test@orcl < /home/test/test.sql >>/home/log/test.log
echo "end-------------------"
