Following was an intresting observation when creating table variables.
1. Table variables are created in tempdb.
2. Table variables are created in tempdb even before the declare table is called.

Steps to find that the Table variables are created in tempdb:
1. Restart your local SQL Server instance. (So that the tempdb gets cleared)
2. Connect to the SQL Server in SQL Server management studio and check if there are any records in sys.objects in tempdb.
[sql]
SELECT * FROM tempdb.sys.tables
[/sql]
You will find there are 0 records(ideally)
3. In a new query window run the below script.
[sql]
USE MASTER
GO

DECLARE @TableVariable TABLE (ID INT,VALUE VARCHAR(100))

INSERT INTO @TableVariable
select 1,’A’

WAITFOR DELAY ’00:02:00′
[/sql]
4. While the above code is getting executed run the below script in other query window.
[sql]
SELECT * FROM tempdb.sys.tables
–Take objectid from the above resultset
SELECT * FROM tempdb.sys.columns where OBJECT_ID = 117575457
[/sql]

Result: It can be found that the tempdb.sys.tables and tempdb.sys.columns has records for the table variable. This proves that the table variable is created in tempdb.

Steps to find that the Table variables are created in tempdb even before the declare table is called:
1. Restart your local SQL Server instance. (So that the tempdb gets cleared)
2. Connect to the SQL Server in SQL Server management studio and check if there are any records in sys.objects in tempdb.
[sql]
SELECT * FROM tempdb.sys.tables
[/sql]
You will find there are 0 records(ideally)
3.In a new query window run the below script.

[sql]
SELECT * FROM tempdb.sys.tables

DECLARE @TableVariable TABLE (ID INT,VALUE VARCHAR(100))

INSERT INTO @TableVariable
select 1,’A’
[/sql]

Result: It can be found that there is a record in the tempdb.sys.tables even before the DECLARE Statement is executed. This proves that the table variables are created in tempdb even before the declare table is called.

Wishing all the blog readers advanced happy new year. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *