8

我已经使用DBI::dbGetQuery.

即使在真正的查询(不是下面的播放查询)中, select convert(date, date_value) as date_value日期仍然存储为字符。

然后我尝试使用 改变代表日期的字符lubridate::ymd,但是我收到一条消息说

未找到日期值

我也试过了,convert(date, date_value)没用as.Date

require(dplyr)
if (dbExistsTable(con, "##temp", catalog_name = "tempdb")){
  dbRemoveTable(con, "##temp")
}
DBI::dbGetQuery(con, paste(              
"select 
    convert(date, '2013-05-25') as date_value
into ##temp
"))

tbl(con, "##temp")

# Error - date_value not found
tbl(con, "##temp") %>%   mutate(date_value= lubridate::ymd(date_value))

# this works
tbl(con, "##temp") %>%   mutate(temp= date_value) 

# this doesn't work - date value not found
tbl(con, "##temp") %>%   mutate(temp= lubridate::ymd(date_value))

如何将此字段用作日期?

注意:当我在 SQL Server 中编写以下内容时,date_value 显示为日期类型

select 
convert(date, '2013-05-25') as date_value
into #hello

select *
from #hello

exec tempdb..sp_help #hello

针对@Kevin Arseneau 的评论,下图显示了执行show_query() 错误信息

4

1 回答 1

5

几个月前,我正在寻找在 PostgreSQL 上使用lubridate函数 +的解决方案,但没有成功。dplyr意外地,我发现直接在dbplyr编码中使用 DBMS 函数的简单解决方案。

抱歉,我将使用 PostgreSQL 示例,因为我不了解 SQL 服务器功能。在这个例子中,我将在 PostgreSQL DBMS 中创建一个临时表,然后我将使用to_date()PostgreSQL 提供的函数计算一个新列。结果是正在寻找的日期:

# Easy example on postgreSQL
library(tidyverse)
library(dbplyr)
library(RPostgreSQL)

con <- dbConnect(PostgreSQL(), 
                 dbname="postgre",
                 host="localhost",
                 port=5432,
                 user="user",
                 password="pass")

date <- data_frame(date_str = c("20180212", "20180213"))

dbWriteTable(con, "tmp", date, temporary = TRUE)

tbl(con, "tmp") %>% 
# The DBMS function is used here
  mutate(date = to_date(date_str, "YYYYMMDD")) %>% 
# Finally, I collect the data from database to R session
  collect()

#># A tibble: 2 x 3
#>  row.names date_str date      
#>* <chr>     <chr>    <date>    
#>1 1         20180212 2018-02-12
#>2 2         20180213 2018-02-13

您可以尝试使用 的设置SQL Server,并且该 CAST()函数可以将您的字符串转换为日期,如本答案中所述。我希望这对你有帮助。

我希望有一天dplyr/dbplyr可以将这些lubridate功能转换为SQL查询。

于 2018-02-13T23:30:43.773 回答