sqlSave:将数据框的时间戳映射到SQL Server时间戳

13

我正试图使用 sqlSave() 将数据框上传到SQL Server的表中。这个数据框里有一个时间戳,我希望将它映射到SQL Server中的 datetime 列。

我遇到了两个问题:

1. 它会将数据框的时间戳映射为浮点数。

2. 它会创建一个表,但没有数据被上传,我得到了一个错误。

下面是一个示例数据框 mdf:

mdf <- structure(list(run = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("run_00", 
"run_01", "run_02", "run_03", "run_04"), class = "factor"), slot = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("slot 3", "slot 4", "slot 5", 
"slot 6"), class = "factor"), timestamp = structure(c(1320774563, 
1320774624, 1320774686, 1320774747, 1320774809, 1320774871), class = c("POSIXct", 
"POSIXt"), tzone = ""), channel = structure(c(1L, 1L, 1L, 1L, 
1L, 1L), .Label = c("och01", "och02", "och09", "och10"), class = "factor"), 
    variable = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("num_blocks", 
    "num_collection", "num_corr_0", "num_corr_1", "num_uncorr_srow", 
    "post_fec_err_rate", "pre_fec_err_rate"), class = "factor"), 
    value = c(1, 62, 124, 185, 247, 309)), .Names = c("run", 
"slot", "timestamp", "channel", "variable", "value"), row.names = c(NA, 
6L), class = "data.frame")

> mdf
     run   slot           timestamp channel       variable value
1 run_00 slot 3 2011-11-08 12:49:23   och01 num_collection     1
2 run_00 slot 3 2011-11-08 12:50:24   och01 num_collection    62
3 run_00 slot 3 2011-11-08 12:51:26   och01 num_collection   124
4 run_00 slot 3 2011-11-08 12:52:27   och01 num_collection   185
5 run_00 slot 3 2011-11-08 12:53:29   och01 num_collection   247
6 run_00 slot 3 2011-11-08 12:54:31   och01 num_collection   309

当我尝试使用sqlSave将数据保存到SQL Server数据库时,以下是发生的情况...

> sqlSave(dbandle,mdf,tablename="mdf")
Error in sqlSave(dbandle, mdf, tablename = "mdf") : 
  [RODBC] Failed exec in Update
22018 0 [Microsoft][ODBC SQL Server Driver]Invalid character value for cast specification

此外,当我查看表的数据类型时,我没有看到时间戳的“datetime”类型。我不明白为什么RODBC会将POSIXct时间戳映射为除datetime之外的其他类型。

[rownames] [varchar](255) NULL,
[run] [varchar](255) NULL,
[slot] [varchar](255) NULL,
[timestamp] [float] NULL,
[channel] [varchar](255) NULL,
[variable] [varchar](255) NULL,
[value] [float] NULL

我该如何解决这个问题?

1个回答

17

有两个选项:

1)懒惰的方法:让错误发生,表将被创建,并在数据库中手动更改列为datetime。它将在下一次工作。

2)正确的方法:使用varTypes

请注意,通过删除不必要的内容可以简化您的问题。另外,我可能不会在SQL Server中使用列名“timestamp”,因为我见过由于内部时间戳数据类型完全不同而导致的混淆。

library(RODBC)
mdf = data.frame(timestamp=as.POSIXct(Sys.time()))

varTypes = c(timestamp="datetime")
channel = odbcConnect("test")
sqlSave(channel,mdf,rownames=FALSE,append=TRUE,varTypes=varTypes)
close(channel)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接