6

我正在尝试使用以下方法将数据框附加到 sql server 表中:

DBI::dbWriteTable(con_poc, "DEP_EVENTS", data_up, overwrite=FALSE, append = TRUE, verbose = TRUE, rownames = FALSE)

但是我在数据库中“日期”类型的列上出现错误。

    Error in result_insert_dataframe(rs@ptr, values) : 
  nanodbc.cpp:1587: 22003: [Microsoft][ODBC SQL Server Driver]Numeric value out of range 

我之前使用 as.POSIXct(example_date) 格式化了该列,但这似乎只适用于“日期时间”列

任何人都可以帮忙吗?

添加信息:

DEP_EVENTS:
DATA_REGION (varchar(50), not null)
EVENT_ID(PK, bigint, not null)
EVENT_NAME(varchar(200), not null)
FORECAST_STATUS(varchar(50), not null)
FORECAST_CYCLE(date, not null)

data_up <- data.frame(DATA_REGION = "America",
                      EVENT_NAME = "shiny deal",
                      FORECAST_STATUS = "Plan of Record",
                      FORECAST_CYCLE = as.Date("2017-07-07"))

DBI::dbWriteTable(con_poc, "DEP_EVENTS", data_up, overwrite=FALSE, append = TRUE, verbose = TRUE, rownames = FALSE)

Error in result_insert_dataframe(rs@ptr, values) : 
  nanodbc.cpp:1587: 22003: [Microsoft][ODBC SQL Server Driver]Numeric value out of range 

我没有插入主键,因为我在尝试时收到以下错误

Error in result_insert_dataframe(rs@ptr, values) : 
  nanodbc.cpp:1587: 23000: [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert explicit value for identity column in table 'DEP_EVENTS' when IDENTITY_INSERT is set to OFF. 

也应要求:

str(data_up)
'data.frame':   1 obs. of  4 variables:
 $ DATA_REGION    : Factor w/ 1 level "America": 1
 $ EVENT_NAME     : Factor w/ 1 level "shiny deal": 1
 $ FORECAST_STATUS: Factor w/ 1 level "Plan of Record": 1
 $ FORECAST_CYCLE : Date, format: "2017-07-07"

我还尝试将因子列更改为字符,但错误没有变化。

4

1 回答 1

0

使用 RODBC,您可以通过在sqlSave()命令前加上SET IDENTITY_INSERT = ON语句来插入主键列。例如:

con = odbcConnect(MY_DSN)
sqlQuery(con,'SET IDENTITY_INSERT DEP_EVENTS ON')
sqlSave(con, DEP_EVENTS, rownames = FALSE, append = 
        TRUE, verbose = FALSE, fast = FALSE)        
sqlQuery(con,'SET IDENTITY_INSERT DEP_EVENTS OFF')
close(con)
于 2017-10-03T00:00:15.620 回答