我相信我應該能夠做到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,然后洗掉臨時表。我可以使用非臨時表,但我認為有正當理由使用臨時表是有道理的,我想了解為什么這不能或不應該按預期作業。除了從 temps 切換之外,我還可以嘗試以othertable編程方式重構結構,但這很容易對某些列型別產生解釋性錯誤。我不能只插入臨時表,因為有時資料型別映射不完美(例如我應該何時使用nvarchar(max)和/或新列由于是 all- 而不確定NA)。
相關鏈接:
- 使用2013 年的查詢將資料插入臨時表
- https://www.sqlshack.com/select-into-temp-table-statement-in-sql-server/從 2021 年開始
uj5u.com熱心網友回復:
有幾種不同的方法:
- 在您的陳述中使用
immediateargDBI::dbExecute
DBI::dbExecute(conn, "select top 5 * into #local from sometable", immediate=TRUE)
DBI::dbGetQuery(conn, "select * from #local")
- 使用全域臨時表
DBI::dbExecute(conn, "select top 5 * into ##global from sometable")
DBI::dbGetQuery(conn, "select * from ##global")
- 使用 dplyr/dbplyr
tt = tbl(conn, sql("select top 5 * from sometable")) %>% compute()
tt
另見此處:https ://github.com/r-dbi/odbc/issues/127
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430078.html
上一篇:如何統計SQL中專案的常用用法?
下一篇:存盤程序比較兩個表并插入/更新值
