tonyk
tonyk

Reputation: 368

How to write to table with date column with DBI

I'm trying to append a dataframe to a sql server table using:

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

But I am getting an error on a column that is 'date' type in the database.

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

I previously formatted the column using as.POSIXct(example_date) but this only seems to work for 'datetime' columns

Can anyone help?

Adding info:

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 

I'm not inserting the primary key as I get the following error when I try that

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. 

Also as requested:

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"

I also tried changing the factor columns to character but no change in the error.

Upvotes: 6

Views: 2012

Answers (1)

arcstorm
arcstorm

Reputation: 11

Using RODBC you can insert into the primary key column by prefacing your sqlSave() command with a SET IDENTITY_INSERT = ON statement. For example:

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)

Upvotes: 1

Related Questions