将新记录插入表A时,将“活动”列更新为“N”

时间:2018-03-23 18:50:21

标签: sql-server triggers

我有桌子A

FacilityID     CreatedDate       Active
---------------------------------------
   A001        2018-03-21          N
   A001        2018-03-22          Y
   A002        2018-03-21          Y 

如果插入了A001或A002的新FacilityID,则旧记录应变为“N”。

我们可以通过After Insert触发器来实现这一目标吗?

格式化:

Create Trigger [dbo].[TableA_tr]
On [dbo].[Table A]
For INSERT
As
Begin
    Update [dbo].[Table A]
    Join 
    set [Active]='N'
    where [CreatedDate]<

2 个答案:

答案 0 :(得分:2)

USE AFTER INSERT触发器,因为您要插入新记录:

 Create trigger [dbo].[TableA_tr]
    on [dbo].[Table A]
    AFTER INSERT
    AS

    --Update all records with the same facility id that do not match the datetime of the new item
    UPDATE [dbo].[TableA]
    SET Active = 'N'
    FROM    inserted INS
    JOIN    dbo.TableA AS T
            ON  T.row_id = INS.row_id;
    WHERE T.[FacilityId] = INS.FacilityId AND T.[CreatedDate] <> INS.CreatedDate

    GO 

答案 1 :(得分:2)

这是另一种方法。这是基于设置的,如果您插入1或任意数量的行,它仍然可以正常工作。请记住,在每次操作时,sql server触发器触发一次,而不是像其他一些DBMS系统那样每行触发一次。

Create trigger [dbo].[TableA_tr]
    on [dbo].[Table A]
    AFTER INSERT
    AS

    --Update all records with the same facility id that do not match the datetime of the new item
    UPDATE a
    SET Active = 'N'
    from dbo.TableA a
    join inserted i on i.FacilityId = a.FacilityId
                and i.CreatedDate <> a.CreatedDate