I'm trying to insert a data frame into an existing (empty) data table in a Microsoft SQL server using rodbc. The following code fails at the sqlSave stage:
# connect to SQL server
require(RODBC)
close(ch)
ch <- odbcConnect(dsn=...)
# list tables available in database
sqlTables(ch, schema = "dbo")
# get info on table structure
tmp <- sqlColumns(ch, "Currency")
varT <- as.character(tmp$TYPE_NAME)
names(varT) <- as.character(tmp$COLUMN_NAME)
# this does not work
sqlSave(ch, df, tablename = "Currency", append = TRUE, rownames = FALSE,
varTypes=varT, verbose = TRUE, test = FALSE, nastring = NULL, fast = TRUE)
I get the following error:
Error in sqlSave(ch, df, tablename = "Currency", append = TRUE, rownames = FALSE, : unable to append to table ‘Currency’
Here's the complete error message:
sqlSave(ch, df, tablename = "Currency", append = TRUE, rownames = FALSE,
+ varTypes=varT, verbose = TRUE, test = FALSE, nastring = NULL, fast = TRUE)
Query: INSERT INTO "Currency" ( "CurrencyID", "Currency", "CountryID", "InvertSpot" ) VALUES ( ?,?,?,? )
Binding: 'CurrencyID' DataType 4, ColSize 10
Binding: 'Currency' DataType -8, ColSize 3
Binding: 'CountryID' DataType 4, ColSize 10
Binding: 'InvertSpot' DataType 4, ColSize 10
Parameters:
no: 1: CurrencyID 2//no: 2: Currency ARS//no: 3: CountryID 1//no: 4: InvertSpot 0//
sqlwrite returned
[RODBC] Failed exec in Update
23000 547 [Microsoft][ODBC SQL Server Driver][SQL Server]The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Currency_Country". The conflict occurred in database "GlobalMacro", table "dbo.Country", column 'CountryID'.
01000 3621 [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. Query: DROP TABLE "Currency"
Error in sqlSave(ch, df, tablename = "Currency", append = TRUE, rownames = FALSE, :
unable to append to table ‘Currency’
Any recommendations on how to fix this? Thank you