在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
条件是,
如何实现这一目标?
答案 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