How would you decide between using a temporary table, a table variable, and a common table expression for a specific intermediate data processing need within a stored procedure?
Short answer
You would choose a table variable for very small, simple intermediate result sets used briefly within a single batch, a temporary table when you expect a larger amount of data, need indexes, or want to reuse the intermediate result across multiple separate statements, and a…
Advertisement
AModel answer
You would choose a table variable for very small, simple intermediate result sets used briefly within a single batch, a temporary table when you expect a larger amount of data, need indexes, or want to reuse the intermediate result across multiple separate statements, and a common table expression when the intermediate logic is only needed once, immediately within a single following statement, and does not need to persist or be indexed separately.
-- Small, simple case: table variable
DECLARE @Ids TABLE (Id INT);
-- Larger, reused, needs indexing: temporary table
CREATE TABLE #LargeResults (Id INT INDEX IX_Id);
-- Used once, immediately: CTE
WITH FilteredData AS (SELECT * FROM Orders WHERE Amount > 100)
SELECT * FROM FilteredData;Real-world example
A developer building a complex reporting procedure carefully chooses a temporary table for a large intermediate result set that needs to be joined multiple times, while using a simple CTE for a smaller piece of logic only needed once immediately afterward.
Likely follow-ups
- What specific factors should weigh most heavily in this decision for a given scenario?
- Can these three approaches be mixed together within the same stored procedure?
Related topics