Top 10 SQL Server Temporary Table Related Interview Questions Answers
1). What are the 2 types of Temporary Tables in SQL Server? 1. Local Temporary Tables 2. Global Temporary Tables 2 ). What is the dif...
1. Local Temporary Tables
2. Global Temporary Tables
2). What is the difference between Local and Global Temporary Tables?
- Local Temporary Tables:
- Prefixed with a single pound sign (#).
- Local temporary tables are visible to that session of SQL Server which has created it/Exists only for duration of the connection/compound statement.
- Local temporary tables are automatically dropped, when the session that created the temporary tables is closed.
- Global Temporary Tables:
- Prefixed with two pound signs (##).
- Global temporary tables are visible to any user and any connection after being created.
- Global temporary tables are also automatically dropped, when the session that created the temporary tables is closed.
5). How can I check for the existence of a temporary table?
IF object_id('tempdb..##TEMPTABLE') IS NOT NULL
6). Table Variables vs. Temp Tables?
- Table var doesn't have to be memory-resident. Its pages can be moved to tempdb if memory is low
- Rollback doesn't affect table vars
- Table vars don't participate in transactions or locking
- Any DML operations done on table variables are not logged
- No statistics are maintained on table variables
7). Can you create foreign key constraints on temporary tables?
8). Do you have to manually delete temporary tables?
No, temporary tables are automatically dropped, when the session that created the temporary tables is closed. But if you maintain a persistent connection or if connection pooling is enabled, then it is better to explicitly drop the temporary tables you have created.
However, It is generally considered a good coding practice to explicitly drop every temporary table you create.