简体   繁体   中英

R text substitution in odbc sqlquery

I'm trying to use text substitutes in R to put in custom dates with my SQL odbc connect query.

For example, I could change date1 to be 2016-01-31 and the data would automatically execute. However, using bquote text replacement, it doesn't seem to work....

Any ideas?

library("rodbc")
date1 <- c("2016-12-31")

myconn <- odbcConnect("edwPROD",uid="username",pwd="BBBBB")
data1 <- sqlQuery(myconn,"
SELECT  a.*
    FROM (SELECT id
                ,status_code                
                ,rate_plan
                ,publication
                ,active_count
                FROM prod_view.fct_active
                WHERE snap_start_date<=bquote(.date1)
                ) AS a  
")
odbcClose(myconn)

This is a job for package infuser . It allows you to change one part of the SQL request, in this case date1 .

library(infuser)
date1 <- c("2016-12-31")

sql_query_template <- "SELECT  a.*
    FROM (SELECT id
                ,status_code
                ,rate_plan
                ,publication
                ,active_count
                FROM prod_view.fct_active
                WHERE snap_start_date<='{{date1}}'
                ) AS a;"
sql_query <-infuse(sql_query_template, date1=date1)

myconn <- odbcConnect("edwPROD",uid="username",pwd="BBBBB")
data1 <- sqlQuery(myconn,sql_query)
odbcClose(myconn)

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