运行 SQL 来自 R 的脚本,其中变量在 R 中定义

Run SQL script from R with variables defined in R

我有一个 SQL 脚本,我需要 运行 使用 R Studio。但是,我的 SQL 脚本有一个在我的 R 环境中定义的变量。我正在使用 dbGetQuery;但是,我不知道(我也没有找到解决方案)如何传递这些变量。

library(readr)    
library(DBI)    
library(odbc)    
library(RODBC)

#create conection (fake one here)
con <- odbcConnect(...)

dt = Sys.Date()   

df = dbGetQuery(.con, statement = read_file('Query.sql'))

文件 'Query.sql' 引用了 dt。如何让文件识别我的变量 dt?

有几个选项,但我的首选是 "bound parameters"

例如,如果您的 'Query.sql' 看起来像

select ...
from MyTable
where CreatedDateTime > ?

? 是绑定的占位符。

那你可以做

con <- dbConnect(...) # from DBI
df = dbGetQuery(con, statement = read_file('Query.sql'), params = list(dt))

使用更多参数,向 list 添加更多 ? 和更多对象,如

qry <- "select ... where a > ? and b < ?"
newdat <- dbGetQuery(con, qry, params = list(var1, var2))

如果您需要 SQL IN 子句,它会有点冒险,因为它不能完全按照我们的意愿绑定东西。

candidate_values <- c(2020, 1997, 1996, 1901)
qry <- paste("select ... where a > ? and b in (", paste(rep("?", length(candidate_values)), collapse=","), ")")
qry
# [1] "select ... where a > ? and b in ( ?,?,?,? )"
df <- dbGetQuery(con, qry, params = c(list(avar), as.list(candidate_values)))