I usually put these lines at the beginning of my stored procedure, and then at the end.
It is an "exists" check for #temp tables.
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
drop table #MyCoolTempTable
end
Full Example:
(Note the LACK of any "SELECT INTO" statements)
CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
CREATE TABLE #MyCoolTempTable (
MyCoolTempTableKey INT IDENTITY(1,1),
MyValue VARCHAR(128)
)
INSERT INTO #MyCoolTempTable (MyValue)
SELECT LEFT(@@VERSION, 128)
UNION ALL SELECT TOP 3 LEFT(name, 128) FROM sysobjects
INSERT INTO #MyCoolTempTable (MyValue)
SELECT TOP 3 LEFT(name, 128) FROM sysobjects ORDER BY NEWID()
ALTER TABLE #MyCoolTempTable
ADD YetAnotherColumn VARCHAR(128) NOT NULL DEFAULT 'DefaultValueNeededForTheAlterStatement'
INSERT INTO #MyCoolTempTable (MyValue, YetAnotherColumn)
SELECT TOP 3 LEFT(name, 128) , 'AfterTheAlter' FROM sysobjects ORDER BY NEWID()
SELECT MyCoolTempTableKey, MyValue, YetAnotherColumn FROM #MyCoolTempTable
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
SET NOCOUNT OFF;
END
GO
Output ~Sample:
1 Microsoft-SQL-Server-BlahBlahBlah DefaultValueNeededForTheAlterStatement
2 sp_MSalreadyhavegeneration DefaultValueNeededForTheAlterStatement
3 sp_MSwritemergeperfcounter DefaultValueNeededForTheAlterStatement
4 sp_drop_trusted_assembly DefaultValueNeededForTheAlterStatement
5 sp_helplogreader_agent DefaultValueNeededForTheAlterStatement
6 fn_MSorbitmaps DefaultValueNeededForTheAlterStatement
7 sp_check_constraints_rowset DefaultValueNeededForTheAlterStatement
8 fn_varbintohexstr AfterTheAlter
9 sp_MSrepl_check_publisher AfterTheAlter
10 sp_query_store_consistency_check AfterTheAlter
Also, see my answer here (on "what is the SCOPE of a #temp table") : https://stackoverflow.com/a/20105766/214977