日期:2014-05-19  浏览次数:20479 次

insert 触发器
想做一个insert事件触发器

  在表   answer里   多项选择题的答案           字段4
                                                                        a,b,c  
                                                                        a,b,d  
例如把a,b,c               更新   表xx    
                              字段2       字段3
                                a                 1
                                b                 1
                                c                 1
                                d                 0

使得字段3里的相对应项     自动加1




------解决方案--------------------
drop table answer,xxb
go
create table answer(answer varchar(100))

create table xxb(xx varchar(10),cs int)
insert into xxb
select 'a ',1
union all select 'b ',1
union all select 'c ',1
union all select 'd ',0

go
create trigger ti_answer on answer
for insert
as
declare @str varchar(100)
declare cur_tmp cursor for
select answer from inserted
open cur_tmp
fetch next from cur_tmp into @str
while @@fetch_status=0
begin
update xxb
set cs=isnull(cs,0)+1
from xxb
where charindex( ', '+xx+ ', ', ', '+@str+ ', ')> 0
fetch next from cur_tmp into @str
end
close cur_tmp
deallocate cur_tmp
go
insert into answer
select 'a,b,c '
union all select 'a,b,d '

select * from xxb

/*
xx cs
---------- -----------
a 3
b 3
c 2
d 1

(所影响的行数为 4 行)

*/