Db2でファイルからSQLを実行する

ファイルにSQLを記載し、実行する(バッチモード)

ファイル作成

[db2inst1@localhost ~]$ vi file1.sql

-- テーブルが存在する場合はdrop
drop table if exists test;

-- create table
create table test (id int not null primary key,
                   col1 varchar(100));
-- insert
insert into test values (1, '1回目');
insert into test values (2, '2回目');

-- select
select * from test;

表記方法

  • 改行はOK
  • SQL文の最後はセミコロン「;」
  • コメントはハイフン2つ「–」で始める

ファイル実行

[db2inst1@localhost ~]$ db2 -tvf file1.sql
drop table if exists test
DB20000I  The SQL command completed successfully.

create table test (id int not null primary key, col1 varchar(100))
DB20000I  The SQL command completed successfully.

insert into test values (1, '1回目')
DB20000I  The SQL command completed successfully.

insert into test values (2, '2回目')
DB20000I  The SQL command completed successfully.

select * from test

ID          COL1                                                                                                
----------- -----------------------------------------------------------
          1 1回目                                                                                               
          2 2回目                                                                                               

  2 record(s) selected.

コマンド説明

  • -t: 終端文字の指定。デフォルトはセミコロン「;」
  • -v: 入力コマンドを標準出力にエコーする
  • -f: 入力ファイルを指定