通过参数将列表传递给postgresql

时间:2012-10-13 21:00:20

标签: ruby postgresql sh

我使用Ruby通过shell调用postgresql,例如:

%x[ psql -A -F "," -o feeds/tmp.csv -f lib/sql/query.sql -v id_list="#{id_list}" ]

query.sql看起来像但可以更改:

Select *
From tbl_test
Where id in (:id_list)

查询应解析为:

Select *
From tbl_test
Where id in ('a','b','c')

提前致谢。

1 个答案:

答案 0 :(得分:2)

# before
-v id_list="#{id_list}"

# after
# `join` will separate the values in an array with the string provided
# `map...` the block given to map will surround each item with single quotes
-v id_list="#{id_list.map { |i| "'#{i}'" }.join(', ') }"

# When `id` is an INTEGER you want the `IN` list specified without quotes
# SELECT * FROM tbl_test WHERE id IN (1, 2, 3);
-v id_list="#{id_list.map(&:to_i).join(', ') }"