您的位置:首页 > 数据库

SQL Server 学习笔记⑧- 触发器(修改前和修改后的语句插入指定表中)

2015-12-03 09:39 288 查看
--测试数据
create table 表a
(
id int ,
name varchar(10),
price int ,
unit varchar(10),
rem  varchar(10)
)
insert into 表a
select 1,     '宝马',     100 ,    '辆',    '四川' union all
select 2,     '奔驰',      78,     '辆',    '北京' union all
select 3,     '夏利',       6,     '辆',    '上海'

--select * from  表a
create table 表b
(
xgid int,
id int ,
name varchar(10),
price int ,
unit varchar(10),
rem  varchar(10),
alterid int,
alterdate datetime
)
--触发器
create  TRIGGER tr_test
ON  表a
AFTER UPDATE
AS
BEGIN

SET NOCOUNT ON;
declare @maxid int
select @maxid=isnull(MAX(xgid),0)+1 from 表b

insert into 表b
select xgid=@maxid,   id,   name,   price,    unit,    rem,    alterid=0, alterdate=GETDATE()
from deleted

insert into 表b
select xgid=@maxid,   id,   name,   price,    unit,    rem,    alterid=1, alterdate=GETDATE()
from inserted

END
GO
--操作
update 表a set  name='宝马1' from 表a where id =1
--查询
select * from 表b
--结果
/*
xgid        id          name       price       unit       rem        alterid     alterdate
----------- ----------- ---------- ----------- ---------- ---------- ----------- -----------------------
0           1           宝马         100         辆          四川         0           2015-12-03 09:30:20.260
0           1           宝马1        100         辆          四川         1           2015-12-03 09:30:20.260

(2 行受影响)
*/
--操作
update 表a set  name='宝马2' from 表a where id =1
--查询
select * from 表b
--结果
/*
xgid        id          name       price       unit       rem        alterid     alterdate
----------- ----------- ---------- ----------- ---------- ---------- ----------- -----------------------
0           1           宝马         100         辆          四川         0           2015-12-03 09:30:20.260
0           1           宝马1        100         辆          四川         1           2015-12-03 09:30:20.260
1           1           宝马1        100         辆          四川         0           2015-12-03 09:31:33.593
1           1           宝马2        100         辆          四川         1           2015-12-03 09:31:33.593

(4 行受影响)

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息