Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Inserting Data with nested select

Author  Topic 

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2011-02-09 : 08:53:40
Dear Gurus,

I have a table dbo.RequestMaster. I am inserting data and one of the value is an id no. I want to fetch the name value corresponding to the id no and insert it into the Requestmaster table. I know it can be achieved through a insert statement followed by an update. How can I do it in one single insert statement. Want I want to acheive is as follows :-

INSERT INTO [dbo].[RequestMaster] (RequestId, Unitid, RequestNo, RequestDt, RecdDt, RegnDt, Remarks, unittype, dateupdated, updatedby, unit)
VALUES (@cNextId, @cUnit, upper(@cRequestno),
cast(@dRequestDt as datetime),cast(@dRecdDt as datetime), GETDATE(),
upper(@cRemarks), @unittype, getdate(), @uid, (select unit from dbo.unitmaster UNION select institution_name as unit
from dbo.tbglInstmaster where dbo.unitmaster.unitid=@cUnit or
dbo.tbglInstmaster.Id=@cUnit)
;


Hope my intent is clear.
Thanks

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-02-09 : 09:07:53
Try this


INSERT INTO [dbo].[RequestMaster] (RequestId, Unitid, RequestNo, RequestDt, RecdDt, RegnDt, Remarks, unittype, dateupdated, updatedby, unit)
SELECT @cNextId, @cUnit, upper(@cRequestno), cast(@dRequestDt as datetime),cast(@dRecdDt as datetime), GETDATE(), upper(@cRemarks), @unittype, getdate(), @uid, unit from dbo.unitmaster
UNION ALL
select @cNextId, @cUnit, upper(@cRequestno), cast(@dRequestDt as datetime),cast(@dRecdDt as datetime), GETDATE(), upper(@cRemarks), @unittype, getdate(), @uid, institution_name as unit from dbo.tbglInstmaster where dbo.unitmaster.unitid=@cUnit or dbo.tbglInstmaster.Id=@cUnit;


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2011-02-09 : 09:44:23
Hi Madhivanan,

That was a great solution as always.
Thanks
Go to Top of Page

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2011-02-09 : 09:45:08
Madhi,
One point though, can I use union instead of union all?
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-02-10 : 03:19:05
quote:
Originally posted by mayoorsubbu

Madhi,
One point though, can I use union instead of union all?


Yes you can use if you want to remove duplicates

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -