sqlserver触发器insert,delete,update

Posted Coder_小菜

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver触发器insert,delete,update相关的知识,希望对你有一定的参考价值。

-- =============================================
-- Author:        王伟
-- Create date: 2017-07-06
-- Description:    增、删、改开放时间表时,同步数据至考勤安排表
-- =============================================
CREATE TRIGGER [dbo].[TR_LM_SYS_KaiFangShiJian_IDU]
   ON  [dbo].[LM_SYS_KaiFangShiJian]
   FOR INSERT,DELETE,UPDATE
AS 
BEGIN
    --新增
    if(exists(select 1 from inserted) and not exists(select 1 from deleted))
    begin 
        INSERT  INTO LM_KQ_KaoQingAnPai
                ( KaoQingAnPaiID ,
                  ShiYanShiID ,
                  KaiShiRiQi ,
                  JieShuRiQi ,
                  
                  XingQingBianHao ,
                  KaiShiShiJian ,
                  JieShuShiJian ,
                  SystemType ,
                  
                  CreateOn ,
                  CreateDate ,
                  UpdateOn ,
                  UpdateDate
                )
                 SELECT CONVERT(VARCHAR(100), A.KaiFangShiJianID) AS KaiFangShiJianID ,
                        CONVERT(VARCHAR(100), A.ShiYanShiID) AS ShiYanShiID ,
                        A.KaiShiRiQi ,
                        A.JieShuRiQi ,
                        
                        A.XingQingBianHao ,
                        A.KaiShiShiJian ,
                        A.JieShuShiJian ,
                        1 AS SystemType ,
                        
                        NULL ,
                        GETDATE() ,
                        NULL ,
                        GETDATE()
                FROM    Inserted AS A
                        INNER JOIN LM_SYS_ShiYanShiXinXi AS B ON A.ShiYanShiID = B.ShiYanShiID
                        INNER JOIN LM_MJ_Men AS C ON B.MenID = C.MenID
                WHERE   A.ShiFouMoRen = 0
                        AND B.IsDelete = 0
                        AND C.IsDelete = 0;    
    end                         
           
    --删除
    if(not exists(select 1 from inserted) and exists(select 1 from deleted))
    begin
        delete from LM_KQ_KaoQingAnPai 
        where KaoQingAnPaiID in(select KaiFangShiJianID from deleted)
    end
                        
    --更新
    if(exists(select 1 from inserted) and exists(select 1 from deleted))
    begin
        update LM_KQ_KaoQingAnPai set ShiYanShiID=a.KaiFangShiJianID 
        ,KaiShiRiQi=a.KaiShiRiQi,JieShuRiQi=a.JieShuRiQi
        ,XingQingBianHao=a.XingQingBianHao,KaiShiShiJian=a.KaiShiShiJian
        ,JieShuShiJian=a.JieShuShiJian,UpdateDate=GETDATE()
        from inserted a
        where KaoQingAnPaiID=a.KaiFangShiJianID
    end
                                       
END

GO

 

以上是关于sqlserver触发器insert,delete,update的主要内容,如果未能解决你的问题,请参考以下文章

触发器中的inserted表和deleted表

SQLServer触发器

SQLServer之创建DML AFTER INSERT触发器

知识点4

sql插入的操作

sqlserver2005触发器问题