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
Select into and temporary tables in MS SQL Server
In SQL Server, the SELECT INTO TEMP TABLE statement is used to select data from one or more source tables and insert it into a temporary table. Temporary tables are extremely useful when dealing with intermediate results, or when working with subsets of data within a session without modifying or aff
4 min read
SQL Server TEMPORARY TABLE
A temporary SQL table also known as a temp table is created in the database only for a specific session to store the data temporarily which is needed for a short duration of time. In this article, we are going to learn about SQL Server temporary tables, their types, how to use them, and why they are
5 min read
Dynamic SQL in SQL Server
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures.
6 min read
Dynamic Table Name Variable in SQL Server
In SQL Server, the dynamic table name variable is used when the name of the table is not explicitly stated in a query but is set in a variable and used instead. This can be in situations where the user does not know or the executing code does not know the table name beforehand and is only determined
3 min read
SQL | Declare Local Temporary Table
Local temporary tables in SQL are powerful for managing intermediate data during a session or procedure. These tables enable developers to temporarily store results, perform computations, and simplify complex queries. Understanding how to declare, use, and manage local temporary tables effectively c
5 min read
Magic Tables in SQL Server
Magic tables are the temporary logical tables that are created by the SQL server whenever there are insertion or deletion or update( D.M.L) operations. The recently performed operation on the rows gets stored in magic tables automatically. These are not physical table but they are just temporary int
3 min read
What is Temporary Table in SQL?
A temporary table in SQL is an important tool for maintaining intermediate results during query execution. They help store temporary data without affecting the underlying permanent tables. In this article, weâll explore temporary tables in SQL, their types (local vs. global), and how to use them eff
3 min read
How to Update a Column in a Table in SQL Server
In the database management area, updating columns in a table is a normal query and it is important software that ensures the accuracy and integrity of data. Whether we are making spelling corrections, editing or altering existing information, or being attentive to changing requirements, carrying out
4 min read
PostgreSQL - Temporary Table
A PostgreSQL temporary table is a powerful tool for managing session-specific data that only needs to exist for a short duration. Temporary tables are created within a database session or transaction and are automatically dropped when the session ends, making them ideal for intermediate data storage
4 min read
Inserting value for identity column in a temporary table in sql
Temporary tables in SQL are widely used for storing intermediate results during query execution, especially in complex procedures or batch operations. In certain scenarios, we may need to insert values into identity columns of temporary tables. By default, identity columns auto-generate their values
3 min read