Interesting Observation – Declaring Table Variables impact on Tempdb

Posted on : 31-12-2012 | By : Devi Prasad | In : Interview Questions, SQL SERVER VARIABLES, SQLServerPedia Syndication, T-SQL Code Examples

Share:

0


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. 🙂

(Visited 45 times, 1 visits today)



References : Devi Prasad (sqlserverlearner.com)

Need Help On SQL Server?

Cannot Find Solution to your problem (or) If you are looking for some help on SQL Server. Dont worry Click Here to Post your question and solve your issue.


Do you like my blog?

If you liked reading this blog, please help spread the word by sharing this blog with your friends.




Write a comment



Tags: