Search code examples
rrodbc

Global variable inside an sqlQuery


I have a variable that stores a time string.

library(lubridate)
date_n <- today() - years(2)

And I want to use the date_n within the following sqlQuery.

transactions_july <- sqlQuery(con, 
                    "select DATA, VREME, PARTIJA, IZNOS 
from pts  
                    where  DATA > '2016-08-10'")

So basically, date_n would replace the date - '2016-08-10'.

Any ideas?


Solution

  • You can use sprintf

    Just do it:

    transactions_july <- sqlQuery(con, 
                    sprintf("select DATA, VREME, PARTIJA, IZNOS 
                    from pts where  DATA > %s",date_n))
    

    The %s will be replaced by the date_n as you want. And for SQL query you can also use sqldf.