CTE
- CTE is Common table expression
- Temporary result set
- Used for storing result of complex queries
- This table available only for the current query
When to use
To store result of complex queries
To create recursive query
To create recursive query
;With CTE1(Name, Roll, Age)--Params are optional AS ( SELECT Student.Name, Student.Roll, Student.Age from Student ) SELECT * FROM CTE1 --Using CTE WHERE CTE1.Age > 50 ORDER BY CTE1.NAME
Local Temp Table
- This table available only for one sql server session or connection that created this table.
- Drop automatically when session ends or connection close.
- These tables are available to one tab only once created
- These table starts with # sign
CREATE TABLE #LclTmp ( ID int, Name varchar(50), Address varchar(150) ) GO insert into #LclTmp values ( 1, 'Tejpal','jammu'); GO Select * from #LclTmp
Global Temp table
- This table available for all sql server sessions or connections.
- Drop automatically when all sessions have been closed.
- These tables are available to all tabs of sql server once created.
- These table starts with Double ## sign.
- CREATE TABLE ##GblTmp
(
UserID int,
Name varchar(50),
Address varchar(150)
)
GO
insert into ##GblTmp values ( 1, 'Tejpal','jammu');
GO
Select * from ##GblTmp
Table variable
- This table available for a group of query execution.
- Drop automatically when all the queries of the group are executed
- These tables are declared with @ sign
- GO
DECLARE @TableVariable TABLE
(
Id INT IDENTITY(1,1),
GoodsID INT,
Quantity INT
)
--Insert data to Table variable @Tablevariable
INSERT INTO @TableVariable(GoodsId,Quantity)
SELECT DISTINCT ID, Quantity FROM GoodsSales ORDER BY GoodsID ASC
--Select data
Select * from @Tablevariable
--Next batch
GO
Select * from @TableVariable--gives error in next batch
No comments:
Post a Comment