一尘不染

r向SQL查询输入的闪亮日期范围

mysql

我下面有一个SQL查询,它很好。

 Select * from dbo.Employee where StartDate between '08/01/2014' and '08/31/2014' order by StartDate

我正在修改此查询,以便它从闪亮的UI(daterange)输入日期。

sqlQuery(myconn, paste("Select * from dbo.Employee where StartTime between", "'as.character(input$daterange[1])'", "and", "'as.character(input$daterange[2])'", "order by StartTime"))

我得到一个错误

[1,] "22007 241 [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string."
[,2] "[RODBC] ERROR: Could not SQLExecDirect ' Select * from.....                                                 Where StartDate between 'as.character(input$daterange[1])' and 'as.character(input$daterange[2])' order by StartDate '"

不确定如何解决此查询,以便它需要从闪亮的UI中输入日期,需要帮助。


阅读 225

收藏
2020-05-17

共1个答案

一尘不染

sub通过简单地使用正则表达式来使用函数来做到这一点:

my_date1 <- "08/01/2014"
my_date2 <- "08/31/2014"

my_query <- 'Select * from dbo.Employee where StartDate between DATE1 and DATE2 order by StartDate'
my_query <- sub("DATE1",my_date1,my_query);my_query <- sub("DATE2",my_date2,my_query)
# the result of your query is below
noquote(my_query)

# if you want the quotes for dates leave them there
my_query <- 'Select * from dbo.Employee where StartDate between "DATE1" and "DATE2" order by StartDate'
my_query <- sub("DATE1",my_date1,my_query);my_query <- sub("DATE2",my_date2,my_query)
# the result of your query is below
noquote(my_query)


# Now sub the inputs into those variables like so
my_query <- 'Select * from dbo.Employee where StartDate between DATE1 and DATE2 order by StartDate'
my_query <- sub("DATE1",input$daterange[1],my_query);my_query <- sub("DATE2",input$daterange[2],my_query)
noquote(my_query)
2020-05-17