Advertisement
Beginner SQL Server, Temporary Tables & Table Variables

What is a table variable in SQL Server, and how is it declared and used?

Short answer

A table variable is declared using the DECLARE statement with a table data type, similar to declaring any other variable, and behaves somewhat like a temporary table but with a more limited scope tied strictly to the batch or procedure in which it was declared, and it typically…

Save SQL Server mock interview
Advertisement
AModel answer
A table variable is declared using the DECLARE statement with a table data type, similar to declaring any other variable, and behaves somewhat like a temporary table but with a more limited scope tied strictly to the batch or procedure in which it was declared, and it typically does not support the same range of indexing options as a temporary table.
DECLARE @TempOrders TABLE (
  OrderId INT,
  Amount DECIMAL(10,2)
);

INSERT INTO @TempOrders SELECT OrderId, Amount FROM Orders WHERE Status = 'Pending';
Real-world example
A stored procedure uses a table variable to hold a small set of intermediate results needed only within that single procedure call, choosing it over a temporary table for its simpler scope and slightly reduced overhead for small data sets.
Likely follow-ups
  • What is the scope difference between a table variable and a local temporary table?
  • Do table variables support foreign key constraints?
Related topics