我正在进行插入和更新2表。当我插入时,我希望新创建的Id更新新表。
insert into Event(EventName, EventManager, EventManagerShortName, EventTicketId) Values(@eventname, (select ManagerShortName From Manager where ManagerID = @managerid), @eventticketid)
我可以这样做:
set @eventId = select Eventid from Event where EventTicketId = @eventticketid
update ScheduledEvents set EventID = @eventid, IsPaymentCompleted = true, IsCancelled = false where ScheduledDate = @scheduleddate
有没有更好的方法来执行此操作,然后每次使用变量来获取新创建的ID?
答案 0 :(得分:0)
使用SCOPE_IDENTITY()
:http://msdn.microsoft.com/en-us/library/ms190315.aspx
此函数返回当前会话中最后创建的标识值。
insert into Event
(EventName, EventManager, EventManagerShortName, EventTicketId)
Values
(@eventname, (select top 1 ManagerShortName From Manager where ManagerID = @managerid), @eventticketid)
set @eventId = scope_identity() --must immediately follow the above line
update ScheduledEvents
set EventID = @eventid
, IsPaymentCompleted = true
, IsCancelled = false
where ScheduledDate = @scheduleddate