gpt4 book ai didi

sql-server - 如何使用 R 中的函数 sqlSave() 将数据附加到具有 IDENTITY 主键的 SQL Server 表?

转载 作者:行者123 更新时间:2023-12-02 07:31:51 25 4
gpt4 key购买 nike

我在 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 ,但没有公认的解决方案。

最佳答案

我无法使用 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()

关于sql-server - 如何使用 R 中的函数 sqlSave() 将数据附加到具有 IDENTITY 主键的 SQL Server 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com