触发器!(简单问题)
没用过触发器~~嘿嘿
如果希望把一个表中删除 添加 修改的记录全部都插入另一个表中,怎么写触发器!
写小例子~~谢谢
问题点数:20、回复次数:4Top
1 楼samfeng_2003(凤翼天翔)回复于 2006-02-15 16:13:08 得分 8
create table t
(id int identity(1,1),col varchar(20))
create table t1
(id int identity(1,1),t_id int,col1 varchar(20))
go
create trigger t_i_u_d
on t
for insert,update,delete
as
set xact_abort on
begin tran
insert t1(t_id,col1)
select * from inserted
union all
select * from deleted
commit tran
go
insert t values ('234')
insert t values ('345')
update t set col='567' where col='234'
delete from t
select * from t1
drop trigger t_i_u_d
drop table t1,t
id t_id col1
----------- ----------- --------------------
1 1 234
2 2 345
3 1 567
4 1 234
5 1 567
6 2 345
(所影响的行数为 6 行)Top
2 楼scmail81(琳·风の狼(修罗))回复于 2006-02-15 16:17:07 得分 6
Try:
create table A
(
id int,
content varchar(10),
status bit
)
create table B
(
id int,
content varchar(10),
status bit
)
drop TRIGGER TEMP_SC
CREATE TRIGGER TEMP_SC on A
AFTER Insert,Update,delete
as
if exists(select 1 from inserted)
begin
insert B select * from inserted where id not in (select id from B)
update B set content=I.content, status =I.status
from inserted I ,B
where B.id=I.Id
end
else
delete B from B where id in (select id from deleted)
Top
3 楼zlp321002(Life Is Good,Let's Shine)回复于 2006-02-15 16:28:28 得分 6
--环境
Create table E(A int ,B varchar(10))
Create table G(A int ,B varchar(10))
--触发器
create TRIGGER TR_E ON [dbo].[E]
FOR Insert,update,delete
AS
--添加
if not exists(select 1 from deleted)
begin
insert G(A,B) select A,B from inserted
end
--更新
if exists(select 1 from inserted) and exists(select 1 from deleted)
begin
insert G(A,B) select A,B from inserted I
end
--删除
if not exists(select 1 from inserted)
begin
insert G(A,B) select A,B from deleted
endTop
4 楼robot2005(小艾)回复于 2006-02-15 16:48:50 得分 0
如果插入另一个表信息后,需要在这个表中记录操作的时间~如何将当前时间获得!~?谢谢Top




