插入两个表后触发

时间:2015-04-28 21:53:24

标签: tsql triggers sql-server-2008-r2

我现在有以下触发器,但我现在要求只有当另一个表Facility有一个记录插入其中且位置ID ='ER' -

时才启动触发器

根据评论,我更新了触发器 -

ALTER TRIGGER [dbo].[VoceraOeOrders] ON [dbo].[OeOrders]
FOR INSERT
AS
IF NOT EXISTS (
        SELECT *
        FROM dbo.Facility
        WHERE LocationID = 'ER'
        )
    RETURN

DECLARE @priority VARCHAR(50)
DECLARE @cat VARCHAR(50)
DECLARE @order VARCHAR(50)
DECLARE @procedure VARCHAR(50)
DECLARE @orderid VARCHAR(50)
DECLARE @locationid VARCHAR(10)
DECLARE @roomid VARCHAR(10)
DECLARE @visitid VARCHAR(50)

SELECT @visitid = VisitID
    ,@priority = Priority
    ,@cat = Category
    ,@procedure = OrderedProcedureName
    ,@order = OrderDateTime
    ,@orderid = OrderNumber
    ,@locationid = (
        SELECT LocationID
        FROM dbo.Facility
        WHERE VisitID = @visitid
        )
    ,@roomid = (
        SELECT CASE 
                WHEN RoomTreatmentID IS NULL
                    THEN 'No Room#'
                ELSE RoomTreatmentID
                END
        FROM dbo.Facility
        WHERE VisitID = @visitid
        )
FROM insterted
WHERE @priority = 'STAT'
    AND @cat IN (
        'CT'
        ,'MRI'
        ,'XRAY'
        ,'US'
        ,'RT'
        ,'NUC'
        ,'ECHO'
        )


BEGIN
    DECLARE @msg VARCHAR(500)
    DECLARE @subject VARCHAR(500)

    SET @msg = @procedure + ' - ' + @locationid + ' ' + @roomid + '-' + ' Priority ' + @priority + '.' + 'Order DateTime/Number ' + @order + '/' + @orderid
    SET @subject = 'Vocera Group Name Here'

    EXEC msdb.dbo.sp_send_dbmail @recipients = N'some_email'
        ,@body = @msg
        ,@subject = @subject
        ,@profile_name = 'Alert'
END

1 个答案:

答案 0 :(得分:2)

只需在触发开头添加:

if not exists(select * from facilities where FacilityID = 'ER')
return

你不能停止踢扳机。您可以检查某些条件并从触发器返回。