使用SQLServer与odbc R包连接到数据库时日期的行为

时间:2018-01-16 21:11:00

标签: sql-server r jdbc odbc

我正在开发一个使用SQL数据库跟踪任务和日期的应用程序。我的应用程序目前使用RSQLServer包连接到数据库,因为我可以在Windows和Linux上使用它。我注意到它没有一致地存储日期。

这是我的MWE(ish - 数据库连接必须自己设置)。

library(DBI)
library(dplyr)
library(lubridate)

# --- Connect to the database via RSQLServer and odbc --------------------------
db <- "your SQL database"
server <- "your SQL server"
conn <- dbConnect(RSQLServer::SQLServer(), server = server, database = db,
                  properties = list(user = "", password = "",
                                    useNTLMv2 = TRUE, domain = "")
)

conn2 <- dbConnect(odbc::odbc(), dsn = "")

# --- Create the test table ----------------------------------------------------
dplyr::db_drop_table(conn, "TestTable")

if (!dbExistsTable(conn, "TestTable")) {
  TestProcessStr <- "
  CREATE TABLE TestTable(
  Process_ID INT NOT NULL IDENTITY(1,1),
  Start_Dt DATE NOT NULL,
  End_Dt DATE DEFAULT '9999-12-31',
  Comment VARCHAR(30),
  PRIMARY KEY( Process_ID )
  );"

  dbExecute(conn, TestProcessStr)
} else {
  message("TestTable exists")
}

# --- Write to test table using different connections --------------------------

rowadd <- data_frame(Start_Dt = Sys.Date(), End_Dt = Sys.Date() + months(3),
                     Comment = "SQLServer, Date as Date")

write_res <- dbWriteTable(conn, name = "TestTable", 
                          value = rowadd, append = T)

# Convert all dates to character
rowadd <- rowadd %>% mutate_if(is.Date, as.character) %>%
  mutate(Comment = "SQLServer, Date as Char")

write_res <- dbWriteTable(conn, name = "TestTable", 
                          value = rowadd, append = T)

rowadd <- data_frame(Start_Dt = Sys.Date(), End_Dt = Sys.Date() + months(3)) %>%
  mutate(Comment = "ODBC, Date as Date")

write_res <- dbWriteTable(conn2, name = "TestTable", 
                          value = rowadd, append = T)


# Convert all dates to character
rowadd <- rowadd %>% mutate_if(is.Date, as.character) %>%
  mutate(Comment = "ODBC, Date as Character")

write_res <- dbWriteTable(conn2, name = "TestTable", 
                          value = rowadd, append = T)


# View database status
ttab <- dbReadTable(conn, "TestTable")
ttab

# --- Disconnect ---------------------------------------------------------------

dbDisconnect(conn)
dbDisconnect(conn2)

这会在我的机器上产生以下输出:

> ttab
  Process_ID   Start_Dt     End_Dt                 Comment
1          1 2018-01-14 2018-04-14 SQLServer, Date as Date
2          2 2018-01-15 2018-04-15 SQLServer, Date as Char
3          3 2018-01-15 2018-04-15      ODBC, Date as Date
4          4 2018-01-15 2018-04-15 ODBC, Date as Character

为什么RSQLServer以Date-as-character对象的方式处理Date对象? odbc::odbc()没有显示相同的行为 - RSQLServer使用的基于java的方法有什么不同吗?

理想情况下,我希望不必在每次写操作之前将所有日期转换为字符串。我无法切换到odbc软件包,因为我无法在Linux上正确配置DSN而无法让我的IT部门参与其中。

0 个答案:

没有答案