R 和 MSSQL - 与临时 tables 的通信(table 未在频道上找到)

R and MSSQL - communication with temp tables (table not found on channel)

我正在尝试通过以下方式使用 RODBC 更新全局温度 table:

library(RODBC)
channel <- odbcConnect("RDataSource", uid = "user", pwd = "password")    
query <- "select * from ##TempTable"
table_data <- sqlQuery(channel, query)
# data frame creation
sqlUpdate(channel, data_frame, index = "id", verbose = TRUE, tablename = "##TempTable")

Select 查询执行良好,但 sqlUpdate 失败并显示错误消息: "Error in odbcTableExists(channel, tablename) : ‘##TempTable’: table not found on channel"

我想这个错误的原因可能与在 temp tables 的名称中使用“#”有关。

UPD:我在使用 sqlSave 函数时遇到了同样的错误。仅当我创建临时 table 时才会发生此错误,通常 SQL table 一切正常。 全局临时 table 正在调用 R 代码之前创建。

那么,有没有什么方法可以使用 sqlSave() 和 sqlUpdate() 等 R 函数与 MSSQL 数据库中的临时 tables 通信?

我终于发现这个错误的原因是ODBC Data Source的设置。似乎使用sqlSave或sqlUpdate等R函数与temp tables通信需要将ODBC数据源中的默认数据库设置为'tempdb'。 所以,现在我可以使用 sqlSave() 函数在 temp table 中插入值。这个函数实际上比使用直接 'INSERT' 查询作为参数的 sqlQuery 函数有更好的性能。