Tuesday, July 15, 2014

Temporary Table -SQL Server

This example Shows you how to create temporary table in SqlServer, Insert values in them, Check their existence and finally Drop them.

Create Temp Table

This one is declared as Global Temporary Table
create table ##YourTempTable (YourTableField1 bigint,YourTableField2 varchar(50))

This one is declared as Local Temporary Table
create table #YourTempTable (YourTableField1 bigint,YourTableField2 varchar(50))


Insert Values in Your Temporary Table

insert into ##YourTempTable 
SELECT * FROM  YourDesiredTable

Check Existence of Temporary table


if exists(select * from tempdb.dbo.sysobjects where ID=object_ID(N'tempdb..##YourTempTable  '))


Check Existence n Then Drop Temporary Table


if exists(select * from tempdb.dbo.sysobjects where ID=object_ID(N'tempdb..##YourTempTable  '))
BEGIN
DROP TABLE ##YourTempTable 

END