题要:主要是自己心血来潮,觉得自己没学一个东西,研究一个东西都要好好的学习,然后做记录。这样可以让以后再回头来看的时候,会忆起曾经学习的点滴,心情肯定也有另外一番风景。
--学习触发器
--作者:中文名:万泽贵 英文名:wodner 网名昵称:用心生活
--建立时间:2010-08-27 10:31
--目的:用于以后翻看平时学习的点滴记录
--建立测试表student(学生表)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[student]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[student]
GO
CREATE TABLE [dbo].[student] (
[studentID] [int] IDENTITY (1, 1) NOT NULL ,
[stuName] [varchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[stuSex] [bit] NULL ,
[stuBirthday] [datetime] NULL
) ON [PRIMARY]
GO
--建立测试表studentLog(学生备份表)用于记录学生的信息的修改(包括添加,修改删除等动作的记录)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[studentLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[studentLog]
GO
CREATE TABLE [dbo].[studentLog] (
[studentID] [int] NOT NULL ,
[stuName] [varchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[stuSex] [bit] NULL ,
[stuBirthday] [datetime] NULL ,
[logDate] [datetime] default getdate(),--动作日期
[flg] [varchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,--新旧数据:old ,new
[Action] [varchar] (10) COLLATE Chinese_PRC_CI_AS NULL --动作:添加,修改,删除
) ON [PRIMARY]
GO
--建立触发器,为添加,删除,修改动作建立触发代码,用于记录于学生信息备份表中(studentlog)
--创建触发器
CREATE TRIGGER trigger_Student ON student
for update,delete,insert
AS
--update --old
IF EXISTS(select *from inserted d)--若插入表有数据,表明是更新或者添加动作
INSERT INTO studentLog(studentID,stuName,stuSex,stuBirthday,flg,[action])
SELECT studentID,stuName,stuSex,stuBirthday,'old','update' FROM deleted del
--update --new
INSERT INTO studentLog(studentID,stuName,stuSex,stuBirthday,flg,[action])
SELECT studentID,stuName,stuSex,stuBirthday,'new','update' FROM inserted ins
--delete
IF NOT EXISTS(select *from inserted d) --若插入表 无数据,表明是删除动作
INSERT INTO studentLog(studentID,stuName,stuSex,stuBirthday,flg,[action])
SELECT studentID,stuName,stuSex,stuBirthday,'old','delete' FROM deleted del
--add
IF NOT EXISTS(select *from deleted de)--若删除表无数据,表明是添加动作
--保存最新的数据
INSERT INTO studentLog(studentID,stuName,stuSex,stuBirthday,flg,[action])
SELECT studentID,stuName,stuSex,stuBirthday,'new','add' FROM inserted ins
--测试数据 添加动作
insert into student values('张三',1,'1986-06-28')
insert into student values('王五',1,'1986-06-29')
insert into student values('李四',1,'1986-06-30')
--测试数据 修改动作
update student set stuSex=1 where studentID=2
--测试数据 删除动作
delete from student where studentID=3
SELECT *FROM studentlog