Search code examples
sql-serverrrodbc

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


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.


Solution

  • 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()