[英]R- variable in ODBC query
I need to run multiple queries to get data from SQL server to R for multiple periods. 我需要运行多个查询以将数据从SQL Server多次获取到R。 I would like to use the period asa variable inside the query in sqlQuery function.
我想在sqlQuery函数的查询中使用句点作为变量。
My query is the following: 我的查询如下:
fld_fec_car<-sqlQuery(dbNGC, "select fld_fec_car
from neptuno.data_mart.[dbo].[tbl_periodo_asig]
where fld_cod_emp='tg'
and fld_periodo ='072014'")
And I would like to have sth like 我想……
per='072014'
fld_fec_car<-sqlQuery(dbNGC, "select fld_fec_car
from neptuno.data_mart.[dbo].[tbl_periodo_asig]
where fld_cod_emp='tg'
and fld_periodo =&per")
Is it possible to include a variable value inside the sqlQuery function? 是否可以在sqlQuery函数中包含变量值? Thanks.
谢谢。
There might be a more elegant solution, but what I usually do is make a function to generate the query text based on input: 可能会有一个更优雅的解决方案,但是我通常要做的是使函数根据输入生成查询文本:
genQuery <- function(arg)
{
lhs <- "select fld_fec_car
from neptuno.data_mart.[dbo].[tbl_periodo_asig]
where fld_cod_emp='tg'
and fld_periodo ='"
rhs <- "';"
##
Query <- paste0(lhs,arg,rhs)
Query <- gsub("\n"," ",Query)
Query <- gsub("\t"," ",Query)
return(Query)
}
##
> genQuery(123)
[1] "select fld_fec_car from neptuno.data_mart.[dbo].[tbl_periodo_asig] where fld_cod_emp='tg' and fld_periodo ='123';"
> genQuery(436)
[1] "select fld_fec_car from neptuno.data_mart.[dbo].[tbl_periodo_asig] where fld_cod_emp='tg' and fld_periodo ='436';"
The gsub("\\n"," ",...)
and gsub("\\t"," ",...)
are just to get get rid of the newline and tab characters - my SQL client doesn't accept them; gsub("\\n"," ",...)
和gsub("\\t"," ",...)
只是为了摆脱换行符和制表符-我的SQL客户端不接受他们; yours might be different. 您的可能会有所不同。
I Used paste: 我用粘贴:
a<-paste("SELECT fld_fec_car FROM neptuno.data_mart.[dbo].[tbl_periodo_asig] where fld_cod_emp='tg' and fld_periodo='", per, "'", sep='')
and then 接着
sqlQuery(dbNGC, a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.