How to append data to a SQL Server table with IDENTITY primary key using function sqlSave() in R?

醉酒当歌 提交于 2019-12-23 11:46:46

问题


I created a table in SQL Server as follows:

CREATE TABLE testPK 
(
    ID INT NOT NULL IDENTITY (1, 1) PRIMARY KEY,
    NumVal NUMERIC (18, 4)
)

Now I want to append data to testPK from an R program using the RODBC function sqlSave() as follows:

# Specify data to append
test.dt <- data.table(NumVal = 1.0)

# Assign connection
myconn <- odbcDriverConnect(connectionString)

# Append test.dt to SQL table testPK
sqlSave(channel = myconn, dat = test.dt, tablename = 'testPK',
        rownames = FALSE, append = TRUE)

# Close connection
odbcCloseAll()

However, this returns the error message

Error in odbcUpdate(channel, query, mydata, coldata[m, ], test = test,  : 
  missing columns in 'data'

I didn't provide a value for column ID in my data table because I'm assuming that the IDENTITY specification on that column of my SQL table causes SQL Server to generate a unique value when a new record is appended. How can I achieve this result from R?

The same question has been posted here, but with no accepted solution.


回答1:


I was not able to reach a solution using sqlSave() so I used the approach that is outlined here for appending an arbitrary number of columns to a SQL table. In the case of my single-column data table, the following code achieved the desired result:

# Specify data to append
test.dt <- data.table(NumVal = 1.0)

# Assign connection
myconn <- odbcDriverConnect(connectionString)

# Concatenate the VALUES portion of the query
values <- paste("(", test.dt$NumVal, ")", sep = "", collapse = ",")

# Create the full query
testQuery <- paste("INSERT INTO testPK (NumVal) VALUES", values)

# Append test.dt to SQL table testPK
sqlQuery(channel = myconn, query = testQuery)

# Close connection
odbcCloseAll()


来源:https://stackoverflow.com/questions/47273104/how-to-append-data-to-a-sql-server-table-with-identity-primary-key-using-functio

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