简体   繁体   中英

Using rodbc package to query sql server from R. Need to pass in date/time value into sqlQuery as part of where statement

Using rodbc package to query sql server from R. Need to pass in date/time value into sqlQuery as part of where statement

btime <- "2016-10-17 18:00:00"
etime <- "2016-10-17 19:00:00"

sqlQuery(cn, "select * from [blah].[blah] where metric = 'name' and date_time >= Convert(datetime, **btime**) and date_time <= Convert(datetime, **etime**)")

I recommend the RODBCext package for this:

library(RODBCext)
sqlQuery(cn,
    "select * from [blah].[blah] where metric = ? and date_time >= ? and date_time <= ?",
    data = list("name",
                btime, 
                etime),
    fetch = TRUE,
    stringsAsFactors = FALSE)

RODBCext makes it really easy to use a parameterized query where you can place a ? in the query code where you want to put a parameter. Since your btime and etime are already in the appropriate format for SQL, you can pass them as strings. I also made 'name' a parameter in the query to avoid using quotes in the query (see https://cran.r-project.org/web/packages/RODBCext/vignettes/Parameterized_SQL_queries.html for details).

sqlExecute is a really convenient way to get away from working strings into your queries.

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