我相信我应该能够执行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 ..."不适用于临时表,但我也看到有几个教程演示它可以工作(对他们而言)。
背景:这是一个通用的访问函数,用于插入数据:我插入一个临时表,执行upsert,然后删除临时表。我可以使用非临时表,但我认为在合理的情况下使用临时表有有效的理由,并且我想了解为什么这不能或不应按预期工作。除了切换临时表之外,我还可以尝试通过编程方式重新构建othertable
的结构,但这容易出现某些列类型的解释错误。我不能只插入一个临时表,因为有时数据类型映射不完美(例如当我应该使用nvarchar(max)
和/或当新列是不确定的时候,因为它们全是NA
)。
相关链接:
#
是本地的,而##
是“全局本地”的(对于用户来说)吗?我知道它们何时关闭,这与连接恒定,不间断无关。 多个语句: 遗憾的是,R的DBI
/odbc
不支持多个语句。您有使用R的经验吗? - r2evanstbl(conn, sql("select top 1 * from othertable")) %>% compute()
,它将在数据库上创建一个临时表,其中包含othertable的第一行。如果您将该调用分配给一个对象,比如说tt
,您可以像往常一样使用它。您还可以访问该对象的名称(tt$ops$x$x
),它看起来类似于#dbplyr_005
。 - langtangDBI::dbExecute(mycon, "select top 5 * into ##mytemp from sometable")
,然后是DBI::dbGetQuery(mycon, "select * from ##mytemp")
。这有帮助吗? - langtang