LoginSignup
1
0

More than 5 years have passed since last update.

psqlの変数にクォーテーションをつける方法

Posted at

psqlでファイルからSQLを流して実行するには次のようにする。

$ psql -f hoge.sql

ここでhoge.sqlの中で可変にできる部分を変数で置き換えてpsqlの実行時に渡すには次のようにする。

$ psql -f hoge.sql -v src_table=users

SQLファイルの方は:を付けて参照できる。

hoge.sql
select * from :src_table;

テーブル名などクォーテーションが必要ない文であればこれで問題ない。
問題はcopyfromtoのようにファイル名を書くべき場所でどうやって参照するかだ。

$ psql -f hoge.sql -v user_list_file=users.tsv
hoge.sql
copy users from :user_list_file;

これだとNG。エラーが出る。
じゃあ、こうかなと思って書いてみるが、

hoge.sql
copy users from ':user_list_file';

当然、これもダメ。

正解はこうする、

hoge.sql
copy users from :'user_list_file';

えっ、そこって場所にクォーテーションをつける。

1
0
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
0