r - dbplyr 将字符更改为临时表中的日期格式

标签 r r-dbi dbplyr

我已使用 DBI::dbGetQuery 将数据提取到 SQL Server 中的临时表中.

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

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

date_value not found



我也试过,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() 的结果
error message

最佳答案

几个月前,我正在寻找使用的解决方案 lubridate功能 + dplyr在 PostgreSQL 上失败。偶然地,我在 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()函数可以将您的字符串转换为日期,如 answer 中所述.我希望这对你有帮助。

我希望有一天dplyr/dbplyr可以翻译lubridate函数到 SQL查询。

关于r - dbplyr 将字符更改为临时表中的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48654069/

相关文章:

r - 是否可以在不给它一个对象的情况下运行一个函数?

R RpostgreSQL bigint 数据类型

sql - 如何在没有数据库连接的情况下从 dbplyr 生成 SQL?

r - dplyr 筛选具有大量匹配项的数据库表

r - 在 R 中运行 map reduce 作业时出错

r - 从条件公式中提取信息

r - 在R中循环时跳过错误

mysql - DBI/RMySQL/RMariaDB 中 dbClearResult() 的用途是什么?

r - 将列添加到 sqlite 数据库

r - Mutate 函数将值向下舍入,为什么?