Temporary Objects in SQL Server
CTE
CTE stands for Common Table expressions. It was introduced
with SQL Server 2005. It is a temporary result set and typically it may be a
result of complex sub-query. Unlike temporary table its life is limited to the
current query. It is defined by using WITH statement. CTE improves readability
and ease in maintenance of complex queries and sub-queries. Always begin CTE
with semicolon.
A sub query without CTE is given
below :
Select * from (
Select a.addrs, e.emp,e.age
from address a inner join employee e on e.eid=a.eid) temp
Where temp.age>30
Order by temp.name
By using CTE above query can be
re-written as follows :
With
cte (address,name,age)
As (
Select
a.addrs, e.emp,e.age from address a inner join employee e on e.eid=a.eid )
Select
* from cte
Where
cte.age>30
Order
by cte.name
When
to use CTE
1.
This is used to store result of a
complex sub query for further use.
2.
This is also used to create a
recursive query.
Temporary Tables
In SQL Server, temporary tables are created at run-time and
you can do all the operations which you can do on a normal table. These tables
are created inside Tempdb database. Based on the scope and behavior temporary
tables are of two types as given below-
1.
Local Temp Table
Local
temp tables are only available to the SQL Server session or connection (means
single user) that created the tables. These are automatically deleted when the
session that created the tables has been closed. Local temporary table name is
stared with single hash ("#") sign.
CREATE TABLE #LocalTemp
(
UserID int,
Name varchar(50),
Address
varchar(150)
)
GO
insert into
#LocalTemp values (
101, 'avinash','bangalore');
GO
Select *
from #LocalTemp
The
scope of Local temp table exist to the current session of current user means to
the current query window. If you will close the current query window or open a
new query window and will try to find above created temp table, it will give
you the error.
2.
Global Temp Table
Global
temp tables are available to all SQL Server sessions or connections (means all
the user). These can be created by any SQL Server connection user and these are
automatically deleted when all the SQL Server connections have been closed.
Global temporary table name is stared with double hash ("##") sign.
CREATE TABLE ##GlobalTemp
(
UserID int,
Name varchar(50),
Address
varchar(150)
)
GO
insert into
##GlobalTemp values (
101, 'avinash','bangalore');
GO
Select *
from #GlobalTemp
Global
temporary tables are visible to all SQL Server connections while Local
temporary tables are visible to only current SQL Server connection.
Table Variable
This acts like a variable and exists for a particular batch
of query execution. It gets dropped once it comes out of batch. This is also
created in the Tempdb database but not the memory. This also allows you to
create primary key, identity at the time of Table variable declaration but not
non-clustered index.
No comments:
Post a Comment