Shell指令碼中擷取SELECT結果值的方法

來源:互聯網
上載者:User

Shell指令碼中擷取SELECT結果值的方法

有時候我們可能會需要在Shell指令碼中執行SELECT語句,並將結果賦值給一個變數,對於這樣的情形,我們可以用以下的方法來達到目的。

#!/bin/ksh
#
# Created : 2015.05.25
# Updated : 2015.05.25
# Author : Jet Chenxi Zhang
# Description : Get SELECT result in Shell

# Variable Definitions #
Oracle_SID=audtest
 ORACLE_HOME=/app/oracle/product/database/11.2.0/db_1
 PATH=$PATH:$ORACLE_HOME/bin
 DBNAME=
 
 # Get Database name by quering v$database #
 DBNMAE=`
 sqlplus -s /nolog <<EOF
 set echo off feedback off heading off underline off;
 conn / as sysdba;
 select name from v\\$database;
 exit;
 EOF`
 
 echo "Database name: "$DBNMAE

如上代碼,可以將擷取Database Name,執行結果如下:

[oracle@hxddcx02 ~]$ ./query_dbname.sh
Database name: AUDTEST

可以看到SELECT的結果已被正確賦值給Shell的變數。如果SELECT中有多個列的值,也可以用此方法,只是需要將結果進行分拆,如用awk:

#!/bin/ksh
#
# Created : 2015.05.25
# Updated : 2015.05.25
# Author : Jet Chenxi Zhang
# Description : Get SELECT results in Shell

# Variable Definitions #
ORACLE_SID=audtest
 ORACLE_HOME=/app/oracle/product/database/11.2.0/db_1
 PATH=$PATH:$ORACLE_HOME/bin
 QUERYRES=
 DBID=
 DBNAME=
 
 # Get Database name by quering v$database #
 QUERYRES=`
 sqlplus -s /nolog <<EOF
 set echo off feedback off heading off underline off;
 conn / as sysdba;
 select dbid, name from v\\$database;
 exit;
 EOF`
 
 DBID=`echo $QUERYRES | awk -F' ' '{print $1}'`
 DBNAME=`echo $QUERYRES | awk -F' ' '{print $2}'`
 echo "Database ID: "$DBID
 echo "Database name: "$DBNAME

運行結果如下:

[oracle@hxddcx02 ~]$ ./query_dbname2.sh
Database ID: 811711272
Database name: AUDTEST

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.