应该简单,触发器的问题。 (我想知道数据修改前和修改后的内容)

kwer 2007-06-19 10:08:48
我想知道表里的一个字段(type),是不是从“1”修改为“0”了,
如果判断是 1->0 ,我会执行某动作,如果不是(例如由0->1 或是由5->0)
则执行其它动作。

...全文
236 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
cassell 2007-06-19
  • 打赏
  • 举报
回复
可是就是不愿看帮助啊,还有那个MSDN,一大堆的扫一眼就不想看的感觉
hellowork 2007-06-19
  • 打赏
  • 举报
回复
TO : cassell()

这些完全可以通过SQLSERVER帮助来了解的.看来你对SQLSERVER还不是很熟,要养成经常查看帮助的好习惯,熟能生巧.
cassell 2007-06-19
  • 打赏
  • 举报
回复
另外,fetch 游标 into .. 是什么意思啊?
select 1,1 union all 这是干什么呢?/不解中,来人解释下麻@<:>@
cassell 2007-06-19
  • 打赏
  • 举报
回复
请问下,还可以用"if not ..." 这样的语句啊?
甚至可以用"if object_id('tbTest') is not null"这样人性化的句子??
hellowork 2007-06-19
  • 打赏
  • 举报
回复
if object_id('tbTest') is not null
drop table tbTest
GO
create table tbTest(id int,type int)
insert tbTest
select 1,1 union all
select 2,1 union all
select 3,5
GO
create trigger trg_insert on tbTest
for update
as
if update(type)
begin
if exists(select 1 from deleted as d inner join inserted as i
on d.id = i.id and d.type = 1 and i.type = 0)
raiserror('从1->0 !',16,1)
else
raiserror('未从1->0',16,1)
end
GO
----测试触发器
update tbTest set type = 0 where id = 1
update tbTest set type = 0 where id = 2
update tbTest set type = 0 where id = 3

drop table tbTest

/*结果
服务器: 消息 50000,级别 16,状态 1,过程 trg_insert,行 8
从1->0 !


服务器: 消息 50000,级别 16,状态 1,过程 trg_insert,行 8
从1->0 !


服务器: 消息 50000,级别 16,状态 1,过程 trg_insert,行 10
未从1->0
*/
kwer 2007-06-19
  • 打赏
  • 举报
回复
谢谢,知道了。

特别是后面的提醒
zjcxc 元老 2007-06-19
  • 打赏
  • 举报
回复
就这么简单
zjcxc 元老 2007-06-19
  • 打赏
  • 举报
回复
-- 一般的写法是这样
create trigger tr_test on 你的表
for update -- 更新时触发
as
if @@rowcount = 0
return -- 无受影响的记录退出

if not update(type) -- 如果没有更新 type , 则退出
return

declare tb cursor local
for
select I.type, D.type
from inserted I, deleted D
where I.主键 = D.主键
open tb
declare @I_type int, @D_type int
fetch tb into @I_type, @D_type
while @@fetch_status = 0
begin
if @I_type = 1 and @D_type = 0 -- 从 0 -> 1
begin
你的处理
end
else
begin
你的处理
end

fetch tb into @I_type, @D_type
end
cose tb
deallocate tb
kwer 2007-06-19
  • 打赏
  • 举报
回复
就这么简单?


zjcxc 元老 2007-06-19
  • 打赏
  • 举报
回复
另外, 楼主只是判断一个列, 并根据值来确定动作, 则必须注意一个 update 影响多行记录的情况, 这种情况下, 触发器只触发一次, inserted 和 deleted 中是所有受影响的记录.

所以要根据业务需要考虑是否要用游标在触发器中循环处理每条受影响的记录.
zjcxc 元老 2007-06-19
  • 打赏
  • 举报
回复
触发器中查询
inserted , 这个逻辑表里面是 更新后的内容
deleted, 这个逻辑表里面是 更新前的内容

34,590

社区成员

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

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