Temporary-Tables

執行整個腳本時出現臨時表錯誤

  • November 16, 2016

我在完整執行以下腳本時遇到問題 - 也就是說,如果我逐行單獨執行它似乎可以工作,但是如果我一次執行所有內容,我會收到錯誤消息“已經有數據庫中名為“#customers”的對象。” 關於為什麼會發生這種情況的任何想法?

if object_id('tempdb..#customers') is not null DROP TABLE #customers
if object_id('tempdb..#temporary_storage') is not null DROP TABLE #temporary_storage

SELECT [customer_number]
 INTO #customers 
 FROM [source_placeholder]

SELECT DISTINCT([customer_number]) AS 'customer_number'
 INTO #temporary_storage 
 FROM #customers 

   IF object_id('tempdb..#customers') is not null DROP TABLE #customers

SELECT * 
INTO #customers
FROM #temporary_storage
if object_id('tempdb..#customers') is not null DROP TABLE #customers
GO
if object_id('tempdb..#temporary_storage') is not null DROP TABLE #temporary_storage
GO

SELECT [customer_number]
 INTO #customers 
 FROM [source_placeholder]

SELECT DISTINCT([customer_number]) AS 'customer_number'
 INTO #temporary_storage 
 FROM #customers 

   IF object_id('tempdb..#customers') is not null DROP TABLE #customers

GO --- End Batch here

SELECT * 
INTO #customers
FROM #temporary_storage

您不能將它們放在一批中,您必須在 drop 語句之間放置一個 GO。

引用自:https://dba.stackexchange.com/questions/155433