select 进入临时 table

select into temporary table

我相信我应该能够做到 select * into #temptable from othertable(其中 #temptable 以前不存在),但它不起作用。假设othertable存在并有有效数据,#sometemp不存在,

# conn <- DBI::dbConnect(...)
DBI::dbExecute(conn, "select top 1 * into #sometemp from othertable")
# [1] 1
DBI::dbGetQuery(conn, "select * from #sometemp")
# Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name '#sometemp'.  [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. 

非临时版本运行没有错误:

DBI::dbExecute(conn, "select top 1 * into sometemp from othertable")
# [1] 1
DBI::dbGetQuery(conn, "select * from sometemp")
### ... valid data ...

系统信息:

conn
# <OdbcConnection> myuser@otherdomain-DATA01
#   Database: dbname
#   Microsoft SQL Server Version: 13.00.5026
DBI::dbGetQuery(conn, "select @@version")
#                                                                                                                                                                                                                          
# 1 Microsoft SQL Server 2016 (SP2) (KB4052908) - 13.0.5026.0 (X64) \n\tMar 18 2018 09:11:49 \n\tCopyright (c) Microsoft Corporation\n\tStandard Edition (64-bit) on Windows Server 2016 Standard 10.0 <X64> (Build 14393: )\n

在 Win11 和 Ubuntu 上测试。 R-4.1.2、DBI-1.1.2、odbc-1.3.3。

我看到一些建议 "select into ..." isn't for temporary tables 的评论,但我也看到一些教程证明它(对他们)有效。

背景故事:这是用于更新数据的通用访问器函数:我插入一个临时文件 table,执行更新插入,然后删除临时文件 table。我可以使用非临时 table,但我认为有充分的理由在合理的情况下使用临时,我想了解为什么这不会或不应该按预期工作。除了从 temps 切换之外,我可以尝试以编程方式重构 othertable 的结构,但这很容易对某些列类型造成解释错误。我不能只插入到临时 table 中,因为有时数据类型映射不完全(例如当我应该使用 nvarchar(max) and/or 时新列由于以下原因而不确定时全部-NA).

相关链接:

有几种不同的方法:

  1. 在您的 DBI::dbExecute 语句中使用 immediate arg
DBI::dbExecute(conn, "select top 5 * into #local from sometable", immediate=TRUE)
DBI::dbGetQuery(conn, "select * from #local")
  1. 使用全局温度table
DBI::dbExecute(conn, "select top 5 * into ##global from sometable")
DBI::dbGetQuery(conn, "select * from ##global")
  1. 使用dplyr/dbplyr
tt = tbl(conn, sql("select top 5 * from sometable")) %>% compute()
tt

另见此处:https://github.com/r-dbi/odbc/issues/127