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.
SELECT * FROM tempdb.sys.tables
You will find there are 0 records(ideally)
3. In a new query window run the below script.
USE MASTER GO DECLARE @TableVariable TABLE (ID INT,VALUE VARCHAR(100)) INSERT INTO @TableVariable select 1,'A' WAITFOR DELAY '00:02:00'
4. While the above code is getting executed run the below script in other query window.
SELECT * FROM tempdb.sys.tables --Take objectid from the above resultset SELECT * FROM tempdb.sys.columns where OBJECT_ID = 117575457
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.
SELECT * FROM tempdb.sys.tables
You will find there are 0 records(ideally)
3.In a new query window run the below script.
SELECT * FROM tempdb.sys.tables DECLARE @TableVariable TABLE (ID INT,VALUE VARCHAR(100)) INSERT INTO @TableVariable select 1,'A'
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.