Temporary Table error when executing entirety of script

temporary-tables

I'm having a problem with running the following script in it's entirety – That is, if I run it line-by-line separately it appears to work, but if I run everything at once, I get the error Message "There is already an object named '#customers' in the database." Any ideas as to why this happens?

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

Best Answer

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

You can't put them in one batch, you have to put a GO between the drop statements.