Temporary Tables
Temporary Tables
Introduction
Temporary Tables are a great T-SQL feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables.
Types of Temporary Tables in SQL
You can create two types of temporary tables in SQL, local and global temporary tables. The two types of temporary tables, local and global, differ from each other in their names, their visibility, and their availability.
Local Temporary Tables
Local temporary tables prefix with single number sign (#) as the first character of their names, like (#table_name).
Local temporary tables are visible only in the current session OR you can say that they are visible only to the current connection for the user.
They are deleted when the user disconnects from instances of Microsoft SQL Server.
Global Temporary Tables
Global temporary tables prefix with double number sign (##) as the first character of their names, like (##table_name).
Global temporary tables are visible to all sessions OR you can say that they are visible to any user after they are created.
They are deleted when all users referencing the table disconnect from Microsoft SQL Server.
Here is syntax for creating temporary table.
Select column1, column2, column3 into temporary table_name from actual table_name
Here we have a table doctor from which we will create a temporary table and will select all columns.
Doctor Table
Doctor_ID | Name | Fee | Timings |
D101 | John | 10000.00 | 8-4 |
D102 | Peter | 20000.00 | 4-8 |
D103 | Nash | 30000.00 | 12-8 |
D104 | Andrew | 25000.00 | 6-12 |
D105 | Smith | 15000.00 | 6-12 |
Now we write sql statement to create temporary table.
select doctor_id as Temp_Doctor_ID,name as Temp_Name,Fee as Temp_Fee,
Timings as Temp_Timings into #Temp_Doctor from doctor
A table will created like this
Temp_Doctor_ID | Temp_Name | Temp_Fee | Temp_Timings |
D101 | John | 10000.00 | 8-4 |
D102 | Peter | 20000.00 | 4-8 |
D103 | Nash | 30000.00 | 12-8 |
D104 | Andrew | 25000.00 | 6-12 |
D105 | Smith | 15000.00 | 6-12 |
Comments
Post a Comment