How to run SQL in a shell script

How to execute SQL command in a shell script when setting a variable? I tried this method and it does not execute the command, it thinks the command is just a string.

#!/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
+4
source share
5 answers
#!/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"
+4
source

You can use heredoc . for example from an invitation:

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

therefore, it sqlpluswill consume everything up to the token EOFas stdin.

+3
source

, , :

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;
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
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 contains the query you want to execute

echo used to display query results

NOTE. You can give multiple requests inside a tag END-OF-SQL, so its also useful for batch execution

0
source

All Articles