我正在学习 R,向 SAS 挥手告别,我对此还是个新手,不知何故我很难找到我正在寻找的东西。
但对于这个具体案例,我读到: Pass R variable to RODBC's sqlQuery? 并让它为我自己工作,只要我只在目标表中插入一个变量。
这是我的代码:
library(RODBC)
channel <- odbcConnect("test")
b <- sqlQuery(channel,
"select top 1 Noinscr
FROM table
where PrixVente > 100
order by datevente desc")
sqlQuery(channel,
paste("insert into TestTable (UniqueID) Values (",b,")", sep = "")
当我用任何其他数字替换 top 1
时,比如说 top 2
,并运行完全相同的代码,我得到以下错误:
[1] "42000 195 [Microsoft][SQL Server Native Client 10.0][SQL Server]
'c' is not a recognized built-in function name."
[2] "[RODBC] ERROR: Could not SQLExecDirect
'insert into TestTable (UniqueID) Values (c(8535735, 8449336))'"
我理解这是因为生成了一个额外的 c,我在给出命令时假定为列:paste(b)
。
那么在使用 paste(b)
时,如何得到 "8535735, 8449336"
而不是 "c(8535735, 8449336)"
?或者还有其他方法吗?
最佳答案
查看 collapse
paste()
中的参数文档。尝试替换 b
与 paste(b, collapse = ", ")
,如下图。
编辑 正如 Joshua 指出的那样,sqlQuery 返回一个 data.frame,而不是一个向量。所以,而不是 paste(b, collapse = ", ")
, 你可以使用 paste(b[[1]], collapse = ", ")
.
library(RODBC)
channel <- odbcConnect("test")
b <- sqlQuery(channel,
"select top 1 Noinscr
FROM table
where PrixVente > 100
order by datevente desc")
sqlQuery(channel,
## note paste(b[[1]], collapse = ", ") in line below
paste("insert into TestTable (UniqueID) Values (", paste(b[[1]], collapse = ", "),")", sep = "")
关于r - 将 R 变量传递给具有多个条目的 RODBC 的 sqlQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8127718/