When we develop an application we often need to provide temporary table functionality in our application.
The requirement is for a master table with an id as the primary key. The other table was a Transaction table that has the foreign key. The master table id should be transfered to the transaction table.
We initially create two tables named MasterTable and TransactionTable.
- Create table MasterTable
- (
- Id int identity(1, 1),
- Name varchar(50)
- )
- Create table TransactionTable
- (
- t_id int identity(1, 1),
- fk_Id int, (Foreign key)
- )
- Create table#tempTest
- (
- Cid int identity(1, 1),
- Id int,
- Name varchar(50)
- )
- Insert into#tempTest(Id, Name)
- select Id, Name from MasterTable
- select * from #tempTest
If there is logic inside a Stored Procedure that involves manipulation of data that cannot be done within a single query, then in such cases, the output of one query or intermediate results can be stored in a temporary table that then participates in further manipulation via joins and so on to achieve the final result. Now we need to transfer the primary key id in the transaction table. To do that we create a loop on the master table to visit all the ids one by one.
- Declare @var int=1
- While @var <= (Select COUNT(*) from #tempTest)
- Begin
- Declare @tempid int
- Select @tempid = Id from #tempTest where Cid=@var
- select @tempid
- Insert into MasterTable(Name)
- Select name from MasterTable where Id=@tempid
- --select * from #tempTest
- set @var=@var+1
- Drop table #tempTest
- END
- Declare @identity int
- set @identity =@@IDENTITY
- --select @identity
- Insert into TransactionTable(fk_Id)
- Select @identity from Acct_Test2 where fk_id=@tempid
- Create Procedure Procedurename
- As
- Create table #tempTest
- (
- Cid int identity (1,1),
- Id int,
- Name varchar(50)
- )
- Insert into #tempTest(Id,Name)
- select Id, Name from MasterTable
- --select COUNT(*) from #tempTest
- select * from #tempTest
- Declare @var int=1
- While @var <= (Select COUNT(*) from #tempTest)
- Begin
- Declare @tempid int
- Select @tempid = Id from #tempTest where Cid=@var
- select @tempid
- Insert into MasterTable(Name)
- Select name from MasterTable where Id=@tempid
- --select * from #tempTest
- Declare @identity int
- set @identity =@@IDENTITY
- --select @identity -76
- Insert into TransactionTable(fk_Id)
- Select @identity from TransactionTable where fk_id=@tempid
- set @var=@var+1
- Drop table #tempTest
- END
- --SELECT * FROM [RTU_Test].[dbo].[MasterTable]
- --Select fk_id from TransactionTable

SubashPosted Aug 25, 2016, 12:35 AM
Good Explanation
Prashant VermaPosted Mar 10, 2016, 3:21 AM
Nice
Prashant VermaPosted Mar 10, 2016, 3:21 AM
keep posting
Prashant VermaPosted Mar 10, 2016, 3:21 AM
nice one
SharadPosted Jul 22, 2015, 12:30 AM
good one...
Rahul Kumar SaxenaPosted Apr 16, 2015, 11:13 AM
good work...
Karthik Muthu KaruppanPosted Apr 14, 2015, 4:33 PM
Nice