Use Temporary Tables and Table Variables in SQL Server
A temporary table is useful when a query needs an intermediate result that you will inspect, index or reuse. A table variable offers a smaller lexical scope for a set of rows. Neither should be selected on the assumption that table variables live only in memory or are always faster.
Create a Local Temporary Table
Run this in one new query session:
CREATE TABLE #WorkItems
(
ItemId int NOT NULL PRIMARY KEY,
Label nvarchar(50) NOT NULL,
IsReady bit NOT NULL
);
INSERT #WorkItems (ItemId, Label, IsReady)
VALUES (1, N'Import', 1), (2, N'Review', 0);
SELECT ItemId, Label
FROM #WorkItems
WHERE IsReady = 1
ORDER BY ItemId;
DROP TABLE #WorkItems;
The query returns item 1, Import. The single # makes the table local to the session, with additional lifetime rules when it is created inside a stored procedure. Separate sessions can use the same local temporary-table name. Drop it when finished, or let the relevant scope end.
Local temporary tables support indexes and statistics. They can be useful for larger intermediate sets whose distribution affects joins and filters. Measure with realistic data rather than inferring performance from this two-row example.
Use a Table Variable in One Batch
DECLARE @Ready TABLE
(
ItemId int NOT NULL PRIMARY KEY,
Label nvarchar(50) NOT NULL
);
INSERT @Ready (ItemId, Label)
VALUES (1, N'Import'), (3, N'Publish');
SELECT ItemId, Label
FROM @Ready
ORDER BY ItemId;
This returns two rows. Keep declaration and use in the same batch. A GO separator ends the batch and therefore the variable's scope. Table variables use tempdb-backed storage and do not have ordinary column statistics. Newer optimization features can improve their estimates, but do not make them interchangeable with temporary tables.
Treat Global Tables as Shared State
A ## prefix creates a global temporary table visible to other sessions on a SQL Server instance. That introduces name collisions and concurrent ownership concerns. Its default cleanup also depends on the creating session ending and active statements releasing references, so it is not accurately described as disappearing instantly when one session closes.
For application work, prefer a local table unless sharing is intentional. If multiple workers need durable, coordinated state, design a normal staging table with explicit ownership and cleanup rather than relying on a global temporary table's lifetime.
Watch Transaction Behavior
Rollback does not undo changes to table variables in the same way it undoes changes to ordinary or temporary tables. Use a # table for a demonstration that must prove rollback restored rows, and test the exact scope and transaction requirements before replacing one construct with another.
Microsoft References
Author: Herman Schoenfeld