简体   繁体   中英

R- variable in ODBC query

I need to run multiple queries to get data from SQL server to R for multiple periods. I would like to use the period asa variable inside the query in sqlQuery function.

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? 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; 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM