简体   繁体   中英

Create date variable for dbGetQuery in R?

basically this is the start of my query/code:

dbGetQuery(con,'SELECT user_id, unique_id
where order_date > parse_datetime('2021-11-01')')

(took out a load because this gets the point across).

The query is quite long and uses the date from above a good few times. So I was wondering if I can create a variable and replace the date.

Something in the format:

date_variable <- 2021-11-01

dbGetQuery(con,'SELECT user_id, unique_id
where order_date > parse_datetime('date_variable')')

I am very new to R and don't really know what I'm doing so any help would be appreciated!

Thanks!

Yes, you can. I prefer to use glue package for this:

library(glue)
library(DBI)

date_variable <- as.Date("2021-11-01")

query <- glue_sql("SELECT user_id, unique_id where order_date > parse_datetime({date_variable})",
         date_variable = date_variable,
         .con = con)

dbGetQuery(con, query)

This source can be interesting for you: Run Queries Safely

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