触发两个表

时间:2016-11-16 16:29:58

标签: sql-server triggers

我有一个包含多个表格的飞行数据库。我试图触发拒绝在有维护请求的航班上插入或更新。如果要求维修飞机,则在这些时间之间不应有飞行。我收到错误消息就好了,但似乎我总是得到它。怎么会?在此先感谢,我一直很感激帮助。

alter trigger DateMaintenanceTrigger 
on Flight
after update, insert 
as
    select 
        m.StartDate, m.TargetEndDate, f.DepartureDateID
    from 
        Maintenance.MaintenanceRequest as m
    inner join 
        Flight as f on f.PlaneID = m.PlaneID
    where 
        f.DepartureDateID < m.TargetEndDate 
        and f.DepartureDateID > m.StartDate

    begin 
        raiserror ('Flight cannot take place on this maintentance date, plane not ready.', 16,1);
        rollback transaction;
        return
    end;
    go


insert into Flight 
values (304, 3, 1, 200192, 1, '20160916 09:00:00 AM');

2 个答案:

答案 0 :(得分:0)

上述问题正在发生,因为您错过了IF条款,并且您正在加入完整的航班表,即如果atlease one flight符合您的标准,您将收到错误。要正确实现,您需要使用inserted.PlaneID加入,如下所示

alter trigger DateMaintenanceTrigger on Flight
after update, insert 
as
IF EXISTS (
select m.StartDate, m.TargetEndDate, f.DepartureDateID
from Maintenance.MaintenanceRequest as m
JOIN inserted as i
ON i.PlaneID = m.PlaneID
and i.DepartureDateID < m.TargetEndDate and i.DepartureDateID > m.StartDate
)
    begin 
        raiserror ('Flight cannot take place on this maintentance date, plane not ready.', 16,1);
        rollback transaction;
        return
    end;
    go



insert into Flight values (304, 3, 1, 200192, 1, '20160916 09:00:00 AM');

答案 1 :(得分:0)

我希望你现在解决了,但如果不是,我可以尝试帮助。尝试这样做,我尝试本地只是一个真/假查询,它应该工作只要你的查询是好的,我不太确定哪个最正确的顺便回滚,现在我把它放在catch函数中但也许在raiserror()之前更好。

alter trigger DateMaintenanceTrigger 
on Flight
after update, insert 
as

BEGIN TRY  
    IF EXISTS(
        select 
            m.StartDate, m.TargetEndDate, f.DepartureDateID
        from 
            Maintenance.MaintenanceRequest as m
        inner join 
            Flight as f on f.PlaneID = m.PlaneID
        where 
            f.DepartureDateID < m.TargetEndDate 
            and f.DepartureDateID > m.StartDate
    )
    BEGIN
        raiserror ('Flight cannot take place on this maintentance date, plane not ready.', 16,1);
    END
    ELSE
    BEGIN
        insert into Flight values (304, 3, 1, 200192, 1, '20160916 09:00:00 AM');
    END
END TRY
BEGIN CATCH  
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SET @ErrorMessage = ERROR_MESSAGE();  
    SET @ErrorSeverity = ERROR_SEVERITY();  
    SET @ErrorState = ERROR_STATE();  

    rollback transaction;

    RAISERROR (@ErrorMessage,  
               @ErrorSeverity, 
               @ErrorState 
               );  
END CATCH;