Unable to append to SQL Server table using sqlSave in R

[亡魂溺海] 提交于 2019-12-05 09:48:36
Linda

There is a possibility of data types and Column names being a problem. So It's best to obtain the datatypes and column names of the table and assign them to the data frame.

ColumnsOfTable       <- sqlColumns(conn, tablename)
varTypes             <- as.character(ColumnsOfTable$TYPE_NAME) 
names(varTypes)      <- as.character(ColumnsOfTable$COLUMN_NAME) 
colnames(dataObject) <- as.character(ColumnsOfTable$COLUMN_NAME)

sqlSave(conn, dataObject, tableNames, fast=TRUE,append=TRUE,  rownames=FALSE, varTypes=varTypes )

The reason I had this problem is: I was trying to append to a table that had an auto-incrementing identity column. If I omitted this column from the data frame it would give me this error missing columns in 'data'. If I made this column NA it would give me Invalid character value for cast specification I was able to troubleshoot with verbose=TRUE. To solve, create a VIEW from the table that has all the columns except the primary key so you can append to this VIEW instead of the table, then you do not need to append the primary key. in my case, the view is called "insert_view"

var_Types <- as.character(as.character(c("int","int","varchar(50)","nvarchar(MAX)")))

names(var_Types) <- as.character(ColumnsOfTable$COLUMN_NAME)

sqlSave(ch, dataframe, "dbo.insert_view",rownames=FALSE,append = TRUE,varTypes=var_Types,verbose = TRUE)

Check using verbose=TRUE in sqlSave argument if any of the columnames in the insert query has the same that you have in your original table.

In my table I used to have a columname with space (the same if it has numbers o different character). It won´t work because sqlSave will remove those character when it creates the query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!