我使用Microsoft SQL Server Management Studio在T-SQL中编写了一个触发器,在我发现一个漏洞之后,我缩小了触发器的范围。这使我的一个触发器停止工作,我无法弄清楚原因。
工作流应该是这样的:删除事件,通过EventId上的外键,删除EventEquipment。由于不再需要设备,因此应将NumberofEquipmentNeeded添加回名为EquipmentAvailabilities的表中设备的可用性。
以下是我的代码。我在插入工作时具有reduce可用性,并且在删除工作之后添加了可用性,直到我添加到仅执行该日期
create trigger trgAddNumberAvailable
on EventEquipments
after delete
as
begin
declare @eventEquipmentId int;
select @eventEquipmentId = EventEquipmentId
from deleted;
declare @eventId int;
select @eventId = EventId
from deleted;
--selects the eventID from EventEquipment
declare @eventDate date;
select @eventDate = EventDate
from Events
where Events.EventId = @eventId;
--finds the date for the Event that was chosen above becuase EventEquipment does not contain date
declare @equipmentId int;
select @equipmentId = EquipmentId
from deleted
where deleted.EventEquipmentId = @eventEquipmentId;
declare @numberRequested int;
select @numberRequested = NumberOfEquipmentNeeded
from deleted
where deleted.EventEquipmentId = @eventEquipmentId;
update EquipmentAvailabilities
set NumberAvailable = NumberAvailable + @numberRequested
where EquipmentId = @equipmentId
and EquipmentAvailabilityDate = @eventDate;
--will update the availability for the equipment from insert and the date it is
--available that was chosen from the Event date from the event that was deleted
答案 0 :(得分:0)
你使用了很多次选择..从删除只是为了填充变量。 而是使用一个选择并填充所有变量。
另请注意替代查询。表之间的关系不明确。
create trigger trgAddNumberAvailable
on EventEquipments
after delete
as
begin
declare @eventEquipmentId int;
declare @eventId int;
declare @eventDate date;
declare @equipmentId int;
declare @numberRequested int;
select @eventEquipmentId = EventEquipmentId, @eventId = EventId
,@equipmentId = EquipmentId,@numberRequested = NumberOfEquipmentNeeded
from deleted;
--selects the eventID from EventEquipment
select @eventDate = EventDate
from Events
where Events.EventId = @eventId;
--finds the date for the Event that was chosen above becuase EventEquipment does not contain date
update EquipmentAvailabilities
set NumberAvailable = NumberAvailable + @numberRequested
where EquipmentId = @equipmentId
and EquipmentAvailabilityDate = @eventDate;
--will update the availability for the equipment from insert and the date it is
--available that was chosen from the Event date from the event that was deleted
--OR (alternative query for bulk delete ,(Correct the join))
update EquipmentAvailabilities
set NumberAvailable = NumberAvailable + @numberRequested
from EquipmentAvailabilities EA
inner join deleted d
on ea.EquipmentId = d.equipmentId
inner join Events E
on d.EventId=e.EventId
where
ea.EquipmentAvailabilityDate = e.eventDate;