有没有办法将R中定义的变量传递给RODBC包中的sqlQuery函数?
具体来说,我需要将这样的变量传递给标量/表值函数,存储过程和/或SELECT语句的WHERE子句。
例如,让:
x <- 1 ## user-defined
然后,
example <- sqlQuery(myDB,"SELECT * FROM dbo.my_table_fn (x)")
或者...
example2 <- sqlQuery(myDB,"SELECT * FROM dbo.some_random_table AS foo WHERE foo.ID = x")
或者...
example3 <- sqlQuery(myDB,"EXEC dbo.my_stored_proc (x)")
显然,这些都不起作用,但我认为有一些东西可以实现这种功能。
答案 0 :(得分:18)
构建您想要传递的字符串。而不是
example <- sqlQuery(myDB,"SELECT * FROM dbo.my_table_fn (x)")
DO
example <- sqlQuery(myDB, paste("SELECT * FROM dbo.my_table_fn (",
x, ")", sep=""))
将填写x
。
答案 1 :(得分:3)
如果使用sprintf,则可以使用变量替换轻松构建查询字符串。为了更加易于使用,如果您预先解析该查询字符串(我正在使用stringr),您可以在代码中的多行上编写它。
e.g。
q1 <- sprintf("
SELECT basketid, count(%s)
FROM %s
GROUP BY basketid
"
,item_barcode
,dbo.sales
)
q1 <- str_replace_all(str_replace_all(q1,"\n",""),"\\s+"," ")
df <- sqlQuery(shopping_database, q1)
最近我发现我想通过使用类似Python的string.format()函数来使变量替换更简单,它允许您在字符串中重用和重新排序变量
e.g。
$: w = "He{0}{0}{1} W{1}r{0}d".format("l","o")
$: print(w)
"Hello World"
但是,这个功能似乎不存在于R中,所以我在Twitter上问了一个非常有帮助的小伙伴@kevin_ushey回复了他自己的custom function以便在R中使用。检查它出!
答案 2 :(得分:-1)
试试这个
x <- 1
example2 <- fn$sqlQuery(myDB,"SELECT * FROM dbo.some_random_table AS foo WHERE foo.ID = '$x'")
答案 3 :(得分:-2)
使用更多变量执行此操作:
aaa <- "
SELECT ColOne, ColTwo
FROM TheTable
WHERE HpId = AAAA and
VariableId = BBBB and
convert (date,date ) < 'CCCC'
"
--------------------------
aaa <- gsub ("AAAA", toString(111),aaa)
aaa <- gsub ("BBBB", toString(2222),aaa)
aaa <- gsub ("CCCC", toString (2016-01-01) ,aaa)