我相信我应该能够做到select * into #temptable from othertable
(where #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 ...”不适用于临时表 https://stackoverflow.com/questions/4101739/sql-server-select-into-existing-table#comment4415598_4101739,但我也看到一些教程证明它(对他们)有效。
背景故事:这是用于更新插入数据的通用访问器函数:我插入临时表,执行更新插入,然后删除临时表。我可以使用非临时表,但我认为在合理的情况下有充分的理由使用临时表,并且我想了解为什么这不能或不应该按预期工作。除了从 temps 切换之外,我还可以尝试重构othertable
以编程方式,但这很容易出现某些列类型的解释错误。我不能只是插入临时表,因为有时数据类型映射不完美(例如当我应该使用nvarchar(max)
和/或当新列由于全部-而不确定时NA
).
相关链接:
-
使用查询将数据插入临时表 https://stackoverflow.com/q/20107827/33582722013年起
-
https://www.sqlshack.com/select-into-temp-table-statement-in-sql-server/ https://www.sqlshack.com/select-into-temp-table-statement-in-sql-server/2021年起