如何在MSSQl中执行TRIGGER?

时间:2017-10-20 09:23:00

标签: mysql sql sql-server

在SQL Server中有两个表,如 Student StudentHistory ,如果 Student 表中发生任何更改,Trigger应该更新 StudentHistory 表。

表:

CREATE TABLE Student (
  Id int,
  Name varchar(20),
  Dept varchar(10),
  Age int,
  Cratedby int,
  CreatedTime datetime,
  Modeifideby int,
  ModifiedTime datetime,
  Flag varchar(5)
)

历史表,

CREATE TABLE StudentHistory (
  Id int,
  Actiontaken varchar(50),
  ActionTime dateTime,
  Cratedby int,
)

触发,

CREATE TRIGGER  wsrd.tr_Student on
wsrd.Student
AFTER INSERT
AS

insert into wsrd.StudentHistory
           (Actiontaken,ActionTime,Cratedby) 
    (SELECT concat('Inserted-',i.id),i.CreatedTime,i.Cratedby from wsrd.Student s, inserted i where s.id=i.Id);
GO 

条件是,

  1. 只有在Student表中插入了Modeifideby,ModifiedTime和Flag列时,才能执行触发器。
    1. 如果Id,Name,Dept,age,CreatedTime和Flag插入表示触发器不应该执行。
  2. 如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

CREATE TRIGGER trStudent
ON dbo.[Student]
FOR INSERT
AS 
BEGIN
    INSERT INTO dbo.[StudentHistory]
        (Id, Actiontaken, ActionTime, Cratedby)  
    SELECT i.Id, i.Flag , i.CreatedTime, i.Cratedby 
    FROM inserted i
    WHERE (i.Modeifideby > '' OR i.ModifiedTime > '01-01-1900' or i.Flag > '')
END