日期:2014-05-18  浏览次数:20617 次

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]
go
create table [tb]([value1] varchar(6),[value2] varchar(6),[id] varchar(2),[flag] varchar(4))
insert [tb]
select 'hello','world','1','1' union all
select 'hello','world','2','1' union all
select 'hello','china','3','1' 
go

create trigger tri_tb_upd
on tb
for update
as
if 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
  end
end
go

update tb set flag=2 where id=1

select * from tb
/**
value1 value2 id   flag
------ ------ ---- ----
hello  world  2    1
hello  china  3    1

(2 行受影响)
**/

------解决方案--------------------
SQL SERVER范例开发大全 李俊民
------解决方案--------------------
推荐SQL SERVER 技术内幕
------解决方案--------------------
SQL code

-- create table
create table txdgtwpv
(value1 varchar(7), value2 varchar(7), id int, flag int)

-- create trigger
create trigger tr_txdgtwpv on txdgtwpv
for update
as
begin
  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.id
end


-- case 1
insert into txdgtwpv
select 'hello', 'world', 1, 1 union all
select 'hello', 'world', 2, 1 union all
select 'hello', 'china', 3, 1

update txdgtwpv set flag=2 where id=1

select * from txdgtwpv

value1  value2  id          flag
------- ------- ----------- -----------
hello   world   2           1
hello   china   3           1


-- case 2
truncate table txdgtwpv

insert into txdgtwpv
select 'hello', 'world', 1, 1 union all
select 'hello', 'china', 2, 1

update txdgtwpv set flag=2 where id=1

select * from txdgtwpv

value1  value2  id          flag
------- ------- ----------- -----------
hello   world   1           2
hello   china   2           1