【问题标题】:How to append data to a SQL Server table with IDENTITY primary key using function sqlSave() in R?如何使用 R 中的函数 sqlSave() 将数据附加到具有 IDENTITY 主键的 SQL Server 表中?
【发布时间】:2017-11-13 20:35:28
【问题描述】:

我在 SQL Server 中创建了如下表:

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

现在我想使用 RODBC 函数 sqlSave() 将数据从 R 程序附加到 testPK,如下所示:

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

但是,这会返回错误消息

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

我没有为数据表中的列 ID 提供值,因为我假设我的 SQL 表的该列的 IDENTITY 规范会导致 SQL Server 在追加新记录时生成唯一值。我怎样才能从 R 中获得这个结果?

同样的问题已发布here,但没有被接受的解决方案。

【问题讨论】:

    标签: sql-server r rodbc


    【解决方案1】:

    我无法使用sqlSave() 找到解决方案,因此我使用here 概述的方法将任意数量的列附加到SQL 表。以我的单列数据表为例,下面的代码达到了预期的效果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      相关资源
      最近更新 更多