拳头我正在执行以下R命令,它们从postgresql
返回一组记录col_qry <- paste("select column_name from table1",sep="")
rs_col <- dbSendQuery(r,col_qry)
temp_list <- fetch(rs_col,n=-1)
使用print(temp_list)
column_name
1 col1
2 col2
3 col3
4 col4
现在基于这个返回的数据,我想生成另一个sql语句,应该是这样的
copy (select "col1","col2","col3","col4" from table2 )
当我这样做时
tmp_cp <- paste("copy (select ",col_list,",","from table2",sep="")
并打印此tmp_cp
然后打印一串copy
语句,而不是一个copy
语句打印出来,一个列中的每个列名称就像这样
copy (select col1 from table2 )
copy (select col2 from table2 )
copy (select col3 from table2 )
copy (select col4 from table2 )
and so on...
我只想要一个copy
语句,其中所有列名称一起提及,每个都引用""
并以,
分隔。我怎样才能做到这一点?
更新:当我使用这些声明时
col_list <- toString(shQuote(temp_list$column_name))
tmp_cp <- paste("copy (select ",col_list,",","from table2",sep="")
然后只生成一个语句,但列名在单引号内,而不是双引号,如下所示:
copy (select 'col1','col2','col3','col4' from table2 )
注意:我上面提到过4列,但并不是说只有4列。列可以很多。为了便于解释,我已经显示了4列
答案 0 :(得分:1)
试试这个:
library(gsubfn)
sql <- fn$identity(
"select `toString(shQuote(temp_list$column_name, 'cmd'))` from table2"
)
,并提供:
> sql
[1] "select \"col1\", \"col2\", \"col3\", \"col4\" from table2"
> cat(sql, "\n")
select "col1", "col2", "col3", "col4" from table2
这也可以,也不需要任何包:
sprintf("select %s from table2",
toString(shQuote(temp_list$column_name, 'cmd')))
答案 1 :(得分:0)
带有paste
参数的嵌套collapse
:
paste("copy (select", paste(cols, collapse=", "), "from table2)")
如果您想要引用的列名:
paste("copy (select", paste(shQuote(cols, "cmd"), collapse=", "), "from table2)")