ablog

不器用で落着きのない技術者のメモ

psql でコマンドラインから変数を渡して SQL 内で参照する

psqlコマンドラインから変数を渡して SQL 内で参照する方法。

  • -v オプションで変数を渡し、
psql -v query_id=54321 ...
  • SQL 内では :変数名 で渡された変数を参照する。
select * from SVL_QUERY_METRICS_SUMMARY where query = :query_id;

参考

-v assignment
--set=assignment
--variable=assignment
Perform a variable assignment, like the \set meta-command. Note that you must separate name and value, if any, by an equal sign on the command line. To unset a variable, leave off the equal sign. To set a variable with an empty value, use the equal sign but leave off the value. These assignments are done during command line processing, so variables that reflect connection state will get overwritten later.

PostgreSQL: Documentation: 17: psql