Вопрос

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

Это было полезно?

Решение

Well, that's your problem, buried in the expanded error message - "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Currency_Country". In other words, Currency_Country is a foreign key - something being referenced by your table from another table. As a result, trying to overwrite it is going to cause your query to error out, because a foreign key cannot contain data in table2 (where you're using it as a foreign key) that isn't in table1 (where it's actually contained).

You need to either (a) stop using a foreign key or (b) incorporate this data into the table that the foreign key originates in before attempting to insert it here.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top