2012-10-13 31 views
2

到PostgreSQL,我使用Ruby通過這樣的命令來調用通過外殼的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') 

在此先感謝。

回答

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(', ') }" 
+0

謝謝,比我期待的要簡單得多。 – bmasc