Indeed, you don't need to drop a @local_variable
.
But if you use #local_table
, it can be done, e.g. it's convenient to be able to re-execute a query several times.
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
/*
can DROP here, otherwise will fail with the following error
on re-execution in the same window (I use SSMS DB client):
Msg 2714, Level ..., State ..., Line ...
There is already an object named '#recent_records' in the database.
*/
DROP TABLE #recent_records
;
You can also put your SELECT statement in a TRANSACTION to be able to re-execute without an explicit DROP:
BEGIN TRANSACTION
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
ROLLBACK