Dynamic SQL and Temporary Tables in SQL Server
Last Updated :
09 Jan, 2024
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Data Manipulation Language in SQL. In this article let us discuss Temp Tables or Temporary Tables and their uses with examples.
What is Temp Tables?
Temp Tables are Temporary Tables that are created using a '#' or '##' sign as a prefix to the table name. Temp Tables are generally used in dynamic SQL and are used for storing and manipulating data like using calculations or data concatenation or applying some filtering on the data. The scope of the local temp table is within the current session. But the scope of the global temp table is visible to all sessions and it will be deleted when the SQL Server re-starts or is physically deleted by the user.
Example:
#TempStudent
or
##TempStudent
Types of Temp Tables
When creating Temp Tables, the scope and lifetime of the temporary tables should be taken into consideration. So based on the scope and lifetime Temp Tables can be of two types, namely Local Temp Table and Global Temp Table.
Local Temp Table
The local Temp Table is created with single '#' sign as prefix to the table name.
They are visible only to the session that creates the Temp Table and it is automatically dropped when the session ends.
Example 1:
CREATE TABLE #tmpStudDemo (id INT,StudName varchar(100))
EXEC ('insert #tmpStudDemo values(101,''Bharath'')')
SELECT * FROM #tmpStudDemo
Explanation:
T-SQL code creates a local temporary table #tmpStudDemo
, inserts a single row with values (101, 'Bharath')
into the table using dynamic SQL, and then selects all rows from the table. Local temporary tables are session-specific, and they are automatically dropped when the session that created them ends.
Output:
Local Temp TableExample 2:
Create Local Temp Table using a stored procedure:
Create Procedure TempTabDemo
(
@TTabName varchar(50),
@CodeNo int
)
As
Begin
EXEC (
'create table #' + @TTabName + ' (IdNo int)
insert #' + @TTabName + ' values(' + @CodeNo + ')
insert #' + @TTabName + ' values(' + @CodeNo + '+ 1 )
Select * from #' + @TTabName
)
End
Execute the stored procedure 'TempTabDemo' created above with sample data, as below:
EXEC TempTabDemo 'TempTableDem',101
Explanation:
This stored procedure dynamically creates a local temporary table, inserts rows into it based on the input parameter @CodeNo
, selects data from the table, and performs these actions within a single session. The dynamic SQL allows for flexibility in generating table names and executing the necessary SQL statements.
Output:
Local Temp Table from Stored ProcedureGlobal Temp Table
The Global Temp Table is created using double '##' as prefix to the temporary table name. The global temp table is visible to all sessions. The global temp tables, once created will exist until the SQL Server is re-started or deleted by user. The global Temp Table can be useful in situations like, when we need to share temporary data across multiple sessions. Another important advantage of global Temp Table is that it can be created using dynamic SQL and used from outside of the dynamic SQL, where as Local Temp Tables created from inside a dynamic SQL is not visible outside of the dynamic SQL which created the temp table as its visibility is limited to the session of local SQL created it.
Example of Global Temp Table
We’re going to look at some examples of Global Temp Table to help you understand the topics better.
Exmaple 1:
DECLARE @SQLStatement NVARCHAR (1000);
SET @SQLStatement = 'CREATE TABLE ##MyTempTable (SNo INT,StudName varchar(100));';
EXEC sp_executesql @SQLStatement;
Insert into ##MyTempTable values (101,'Rajesh')
SELECT * FROM ##MyTempTable;
Drop Table ##MyTempTable
Explanation:
This SQL code dynamically creates a global temporary table, inserts a row into it, selects all rows from it, and then drops the table. The use of global temporary tables allows for temporary storage of data that is visible across different sessions, and the table is automatically dropped when the session that created it ends.
Output:
Global Temp TableExample 2:
Create Global Temp Table using a stored procedure:
Create Procedure TempTabGlobalDemo
(
@TTabName varchar(50),
@CodeNo int
)
As
Begin
EXEC (
'create table ##' + @TTabName + ' (IdNo int)
insert ##' + @TTabName + ' values(' + @CodeNo + ')
insert ##' + @TTabName + ' values(' + @CodeNo + '+ 1 )
insert ##' + @TTabName + ' values(' + @CodeNo + '+ 2 )
Select * from ##' + @TTabName
)
EXEC('Drop Table ##' + @TTabName )
End
Execute the stored procedure 'TempTabGlobalDemo' created above with sample data, as below:
EXEC TempTabGlobalDemo 'GTempTableDem',101
Expalantion:
This stored procedure dynamically creates a global temporary table, inserts rows into it based on the input parameter @CodeNo
, selects data from the table, and finally drops the table. The dynamic SQL allows for flexibility in generating table names and executing the necessary SQL statements.
Output:
Global Temp Table from Stored procedureAdvantages of Using Temporary Tables with Dynamic SQL
The Temp Table in SQL Server provides many advantages over the regular SQL Server Database tables. Listed below are the advantages:
- Speed of Execution: While using the Temp Tables the execution of query can be faster as there is less logging and locking overheads for temporary tables.
- Access rights/security of Temp Tables: Temporary tables can be used for insert, update and delete operations on its data or on other tables without any security or access rights concerns.
- No Concurrency Issues: Using Temp Tables avoid any concurrency issues while Data insert, update or delete, as these temporary tables are only visible to the current session.
- Resource Efficient: As the Temp Tables are created and deleted from the same session, they take no memory space permanently and so it is more resource efficient.
- Better Query optimization: The Temp Tables provide better query optimization for data of any size.
Conclusion
In SQL Server creating Temp Tables are useful to save temporary data in the database and manipulate the same data. This will help to avoid memory issues as the Temp Tables are deleted at the end of the session if the Temp Table type is 'Local' and it can save memory usage. Since Temp Tables are created and used in dynamic SQL, care should be taken about any security issues. Whether dealing with intermediate storage or optimizing complex queries, temporary tables are a valuable tool in your SQL Server toolkit.
Similar Reads
SQL Server Basics
Introduction of MS SQL ServerData is a collection of facts and figures and we have humungous data available to the users via the internet and other sources. To manipulate the data, Structured Query Language (SQL) in short has been introduced years ago. There are different versions of SQL available in the market provided by diff
2 min read
Create Database in MS SQL ServerDatabases in Microsoft SQL Server are crucial for managing data, categorized into system databases, which are auto-created and user databases, created by users. In this article, We will learn about the basics of system and user databases along with methods for creating and managing them using T-SQL
5 min read
List All Databases in SQL ServerIn SQL Server, databases are crucial for storing and managing data efficiently. Whether we are managing a large enterprise system or a small application, understanding how to list all the databases on our SQL Server is essential. In this article, we will write SQL queries that help us to retrieve al
3 min read
SQL Data TypesIn SQL, each column must be assigned a data type that defines the kind of data it can store, such as integers, dates, text, or binary values. Choosing the correct data type is crucial for data integrity, query performance and efficient indexing.Benefits of using the right data type:Memory-efficient
3 min read
SQL Server Tables & Schemas
CREATE TABLE in SQL ServerSQL Server provides a variety of data management tools such as querying, indexing, and transaction processing. It supports multiple programming languages and platforms, making it a versatile RDBMS for various applications. With its robust features and reliability, SQL Server is a popular choice for
4 min read
SQL Server Table VariableSQL Server Table variable is a local variable that stores data temporarily, similar to the temporary table in SQL Server. Tempdb database is used to store table variables. How to Declare Table Variable in SQL ServerTo declare a table variable in SQL Server, start the DECLARE statement. The name of t
2 min read
SQL Server DROP TABLEIn SQL Server, the DROP TABLE statement is used to remove or delete permanently from the database. In SQL Server after performing the DROP Operation we cannot revoke the table or database again, because it is an irreversible action. The Drop Operation is different from the DELETE Command, In the DEL
3 min read
Rename Column in SQL ServerSQL Server is a widely used Relational Database Management System (RDBMS) that allows users to create and manage databases effectively. Renaming a column in a database is a common task usually required when users want to change the database schema. In this article, we will explore different methods
3 min read
SQL Server Rename TableIn SQL Server, renaming tables is a frequent operation that we often require during database maintenance or schema changes. This article ensures your seamless transition through the table-renaming process without compromising data integrity. it provides comprehensive guidance and guarantees protecti
3 min read
CREATE SCHEMA in SQL ServerA schema is a collection of database objects like tables, triggers, stored procedures, etc. A schema is connected with a user which is known as the schema owner. The database may have one or more schema. To create a schema in SQL Server use the 'CREATE SCHEMA' Statement. SQL CREATE SCHEMACREATE SCHE
2 min read
SQL Server Queries & Operations
SQL Server Constraints & Keys
SQL Server Indexes & Performance
SQL Server Advanced Topics