当前位置: 代码迷 >> Sql Server >> update触发器设计,该如何处理
  详细解决方案

update触发器设计,该如何处理

热度:38   发布时间:2016-04-27 14:40:42.0
update触发器设计
俺知道触发器很神奇,但水平有限,特来请教大家,另外希望大家推荐几本sql的书学习学习

表结构如下(3行4列):

场景1:
value1 value2 id flag
"hello" "world" 1 1
"hello" "world" 2 1
"hello" "china" 3 1

场景2:
value1 value2 id flag
"hello" "world" 1 1
"hello" "china" 2 1

现在要对 id==1的项的flag进行UPDATE为flag=2(则在两个场景中update的都是第一行)

希望有触发器能自动完成如下操作:
找到表中其它的行,如果还存在 value1和value2与正在改变的行的value1,value2相等的行,则将正在update的行删除

在场景1中,执行完update的结果为(因为还有"hello", "world"):
value1 value2 id flag
"hello" "world" 2 1
"hello" "china" 3 1

在场景2中,执行完update的结果为
value1 value2 id flag
"hello" "world" 1 2
"hello" "china" 2 1


谢谢大家了

------解决方案--------------------
SQL code
if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([value1] varchar(6),[value2] varchar(6),[id] varchar(2),[flag] varchar(4))insert [tb]select 'hello','world','1','1' union allselect 'hello','world','2','1' union allselect 'hello','china','3','1' gocreate trigger tri_tb_updon tbfor updateasif update(flag)begin  if exists(select 1 from tb a,inserted i where a.value1=i.value1 and a.value2=i.value2 and a.id!=i.id)  begin    delete tb    from inserted i where tb.value1=i.value1 and tb.value2=i.value2 and tb.id=i.id  endendgoupdate tb set flag=2 where id=1select * from tb/**value1 value2 id   flag------ ------ ---- ----hello  world  2    1hello  china  3    1(2 行受影响)**/
------解决方案--------------------
SQL SERVER范例开发大全 李俊民
------解决方案--------------------
推荐SQL SERVER 技术内幕
------解决方案--------------------
SQL code
-- create tablecreate table txdgtwpv(value1 varchar(7), value2 varchar(7), id int, flag int)-- create triggercreate trigger tr_txdgtwpv on txdgtwpvfor updateasbegin  if exists(select 1             from txdgtwpv a            inner join inserted b             on a.value1=b.value1 and a.value2=b.value2            and a.id<>b.id)     delete a     from txdgtwpv a     inner join inserted b      on a.value1=b.value1 and a.value2=b.value2     and a.id=b.idend-- case 1insert into txdgtwpvselect 'hello', 'world', 1, 1 union allselect 'hello', 'world', 2, 1 union allselect 'hello', 'china', 3, 1update txdgtwpv set flag=2 where id=1select * from txdgtwpvvalue1  value2  id          flag------- ------- ----------- -----------hello   world   2           1hello   china   3           1-- case 2truncate table txdgtwpvinsert into txdgtwpvselect 'hello', 'world', 1, 1 union allselect 'hello', 'china', 2, 1update txdgtwpv set flag=2 where id=1select * from txdgtwpvvalue1  value2  id          flag------- ------- ----------- -----------hello   world   1           2hello   china   2           1
  相关解决方案