sqlite3でトリガを使う
sqlite3でSQLのトリガを試してみました。使うの初めて。
トリガを使って、ある小さいアプリケーションで使われているDBのテーブルの最終更新時刻を記録したいと思います。
以下は対象となるテーブルのひとつ、scheduleテーブルに行が挿入されたときフィールドを更新するトリガを書いたログ。
参考:http://www.sqlite.org/lang_createtrigger.html
sqlite> .schema CREATE TABLE schedule (id integer primary key autoincrement, category text, topic text, ctime date); ...(略) sqlite> -- 記録先テーブルの作成; sqlite> create table last_update (tablename varchar(255) primary key, lastupdate datetime) sqlite> -- トリガの作成; sqlite> create trigger schedule_insert after insert on schedule begin update last_update set lastupdate = current_timestamp where tablename='schedule'; end; sqlite> -- 確認; sqlite> .schema ...(略) CREATE TRIGGER schedule_insert after insert on schedule begin update last_update set lastupdate = current_timestamp where tablename='schedule'; end; sqlite> -- 初期化; sqlite> insert into last_update values ('schedule', current_timestamp); sqlite> select * from last_update; schedule|2011-01-02 15:33:49 sqlite> -- データの挿入; sqlite> insert into schedule values (null, 'category_sample', 'topic_sample', current_timestamp) sqlite> -- 最終更新時刻が更新されているか確認; sqlite> select * from last_update; schedule|2011-01-02 15:37:32
DBビギナーズ~DBが動く仕組みから開発/運用の基本まで (DB Magazine Selection)
- 作者: DBマガジン編集部
- 出版社/メーカー: 翔泳社
- 発売日: 2010/08/28
- メディア: 大型本
- 購入: 1人 クリック: 7回
- この商品を含むブログ (2件) を見る