这个触发器怎么写?

SixBank 2010-08-11 03:26:10

表S:

字段:
C1 nvarchar,
C2 datetime

表S 修改完(update)的时候,判断C1,如果update前不为NULL 且update后为空则把当前时间写入C2,如果update前为 NULL 且update后不为空则把C2 置空NULL

以上用触发器实现?
...全文
221 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
SixBank 2010-08-12
  • 打赏
  • 举报
回复
经测试,修改为以下达到目的效果,

create trigger trg_upd_c on s
for update
as
if update(c1)
begin
...


instead of update 和 for update 写有什么区别?
xman_78tom 2010-08-11
  • 打赏
  • 举报
回复

-- 触类旁通
if OBJECT_ID('S') is not null
drop table s;
go
create table S (id int identity primary key, c1 varchar(20),c2 varchar(20));
go
insert into s(c1,c2) values(null,'c2');
insert into s(c1,c2) values('c1','c2');
go

create trigger trg_upd_c on s
instead of update
as
if update(c1)
begin
;with t as(
select i.id,i.c1 ic1,i.c2 ic2,d.c1 dc1 from inserted i,deleted d where i.id=d.id
)
update s set c2=
(case when t.dc1 is not null and t.ic1 is null then convert(varchar(20),getdate(),120)
when t.dc1 is null and t.ic1 is not null then null
else t.ic2 end), c1=t.ic1
from s,t where s.id=t.id;
end
go

update s set c1='c1' where id=1;
update s set c1=null where id=2;

select * from s;
SixBank 2010-08-11
  • 打赏
  • 举报
回复
大致明白了,再问下 是不是这样理解?:
deleted是更新前的记录数据吗? 用来与更新后的表内容inserted比较?
SixBank 2010-08-11
  • 打赏
  • 举报
回复
表S:

3个字段吧:
id identity
C1 nvarchar,
C2 datetime

判断的是字段C1 ,然后根据C1的内容更新字段 C2
SixBank 2010-08-11
  • 打赏
  • 举报
回复
谢谢楼上,先试试
xman_78tom 2010-08-11
  • 打赏
  • 举报
回复

-- 要求 s 表上必须有主键,用于唯一标示行
if OBJECT_ID('S') is not null
drop table s;
go
create table S (id int identity primary key, c datetime);
go
insert into s(c) values(null);
insert into s(c) values(GETDATE()-1);
go

create trigger trg_upd_c on s
instead of update
as
if update(c)
begin
;with t as(
select i.id,i.c ic,d.c dc from inserted i,deleted d where i.id=d.id
)
update s set c=
(case when t.dc is not null and t.ic is null then getdate()
when t.dc is null and t.ic is not null then null
else t.ic end)
from s,t where s.id=t.id;
end
go

update s set c=getdate() where id=1;
update s set c=null where id=2;

select * from s;
SixBank 2010-08-11
  • 打赏
  • 举报
回复
以上用触发器不能实现?
SixBank 2010-08-11
  • 打赏
  • 举报
回复
表S 修改完(update)的时候,判断字段C1,如果:
字段C1 在表S update 前不为NULL 且update后为空则把当前时间写入C2,
字段C1 在表S update 前为 NULL 且update后不为空则把C2 置空NULL
samyou 2010-08-11
  • 打赏
  • 举报
回复
这个完全在前台系统进行判断。
飘零一叶 2010-08-11
  • 打赏
  • 举报
回复
instead of 触发器能实现。
表S 修改完(update)的时候,判断C1,如果update前不为NULL 且update后为空则把当前时间写入C2,如果update前为 NULL 且update后不为空则把C2 置空NULL
描述的不是很清晰。

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧