1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MacでSQL*Plusを使ってSPOOLするシェルスクリプト作ったらオプションが効かなかった話

Last updated at Posted at 2018-06-23

本記事の概要

Macを使い始めた頃に、Oracle DBからデータを定期的に収集するシェルスクリプトを作成したらオプションのECHO OFFだけが、なぜか効かないという事象にハマったのでメモとして記載します。
誤りやご質問等ありましたら、コメントお願いします。

1.前提

ご使用の端末がSQL*PlusからOracle DBに接続できる状態となっていること
まだの方はこちらなどがわかりやすいです。
<ご参考>
https://www.tank-sakurai.com/mac-os-x_oracle-database/

2.実行するSQLの準備

まずは、お好きなディレクトリに実行したいSQLを作成して下さい。
今回はホームディレクトリにtoolsを作成し、その中に格納します。
・ディレクトリ:Users/bar/tools

hoge.sql
set colsep ','
set trimspool off
set echo off

spool Users/bar/tools/output.csv

select * from hoge;

spool off

3.実行するシェルスクリプトの準備

お好きなディレクトリにシェルスクリプトを作成して下さい。
今回は手順2で作成したtoolsディレクトリの中に作成します。

hoge.sh
sqlplus -s user/password @ /Users/bar/tools/hoge.sql

4.注意点(ハマったところ)

SQL自体はsqlplusコマンドに対して、SQLスクリプトを標準入力をすることで実行することもできます。
※手順3との違いは「@」が「<」になっていること

hoge.sh
sqlplus -s user/password < /Users/bar/tools/hoge.sql

ただし、この実行方法だとSQL実行オプションのECHO OFFが効かなくなり、SPOOL ON/OFFやSELECT文自体もCSVファイルに出力されてしまう。これはECHOシステム変数がSQLスクリプトファイルを@やSTARTから実行した場合に設定するものだからです。このことに気づくのに1時間くらいかかってしまった...
<Oracle公式>
http://otndnld.oracle.co.jp/document/products/oracle11g/111/doc_dvd/server.111/E05784-01/ch12040.htm#i2698923

5.シェルスクリプトを実行する

という訳で、手順3のシェルスクリプトを実行すると、Users/bar/tools/output.csvが作成され、SQLの実行結果だけが出力されているはずです。

bash
/bin/bash hoge.sh
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?