☆用心生活☆-wonder-{改变自己才能让自己过上不一样的日子。为自己加油!}

SQL之触发器学习记录--(1)

 题要:主要是自己心血来潮,觉得自己没学一个东西,研究一个东西都要好好的学习,然后做记录。这样可以让以后再回头来看的时候,会忆起曾经学习的点滴,心情肯定也有另外一番风景。

--学习触发器
--
作者:中文名:万泽贵 英文名: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

 

posted @ 2010-08-27 10:42  ☆用心生活☆  阅读(484)  评论(0编辑  收藏  举报
本作者写的任何文章均属原创,若要转载,请注明出处;若
进行与文章有关的商业行为,本作者保留拥有诉诸法律追究
侵权的任何行为。文章只代表本人某一学习时间段内对某一
技术的说明,不代表具有绝对的正确性,若要学习,请与各
位高手编程人员讨论学习。本文章也不代表自己某一时期某
一公司的任何专著和机密文件。仅仅提供自我学习和他人学
习的文章参考,以及自我知识记录。wanzegui325#163.com