1

I'm using dbGetQuery in R to fetch result.

df <- dbGetQuery(conn, "SELECT * FROM orders WHERE invoice_date >= '2020-08-31 00:00:00.00000+00'")

I want to assign date to a variable and call it in query. Something like this,

invoice_date <- '2020-08-31 00:00:00.00000+00'
df <- dbGetQuery(conn, "SELECT * FROM orders WHERE invoice_date >= {invoice_date}")

How can I achieve this?

3
  • take a look at the paste() function Commented Sep 4, 2020 at 14:11
  • I tried this code paste("SELECT invoice_date,order_id, product_code, delivery_pincode,fulfilment_center FROM sales_report WHERE invoice_date >= ", invoice_date, "", sep="") but it is not taking as character with quotes Commented Sep 4, 2020 at 14:20
  • After @Waldi's response I tried this with paste option, it works. invoice_date <- "'2020-09-03 00:00:00.00000+00'" df <- dbGetQuery(conn, paste("SELECT invoice_date,order_id, product_code, delivery_pincode,fulfilment_center FROM sales_report WHERE invoice_date >= ", invoice_date, "", sep="") .Thanks !! But I'm accepting @Waldi's answer since it's more cleaner approach. Commented Sep 4, 2020 at 14:31

1 Answer 1

1

The glue package should perfectly fit your needs:

invoice_date <- '2020-08-31 00:00:00.00000+00'
df <- dbGetQuery(conn, glue::glue("SELECT * FROM orders WHERE invoice_date >= '{invoice_date}'"))

Another option is to include the quotes in the variable:

invoice_date <- "'2020-08-31 00:00:00.00000+00'"
df <- dbGetQuery(conn, glue::glue("SELECT * FROM orders WHERE invoice_date >= {invoice_date}"))
Sign up to request clarification or add additional context in comments.

3 Comments

The assigned variable is not taking as character with quotes. I got this error WHERE invoice_date >= 2020-09-04 00:00:00.00000+00 (ERROR: syntax error at or near "00" Position: 137) . Quotes are missing .
what if we have multiple where condition like --> where Material= "car" and invoice_date >= {invoice_date}
@Amit, you could build the where condition as needed, possibly with if statements, for example mycondition <- "where "; mycondition <- paste(myconditon, " Material= 'car'"; mycondition <- paste(mycondition, glue("and invoice_date >= {invoice_date}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.