27,580
社区成员
发帖
与我相关
我的任务
分享
if object_id('tb') is not null
drop table tb
go
create table tb(id int,name varchar(20),num int)
go
create trigger tri_update_num
on tb
for insert
as
begin
update tb set num=(
select count(1) from tb where name=t.name and id<=t.id
) from tb t
end
go
insert into tb(id,name) select 1,'a'
insert into tb (id,name)select 2,'a'
insert into tb (id,name)select 3,'a'
insert into tb(id,name) select 6,'a'
insert into tb (id,name)select 8,'a'
insert into tb (id,name)select 12,'a'
insert into tb (id,name)select 4,'b'
insert into tb (id,name)select 5,'b'
insert into tb (id,name)select 6,'b'
select * from tb
create table ta(id int identity(1,1),vname varchar(10),num int)
go
create trigger tr_name
on ta
for insert
as
update a
set num = (select count(1) from ta where id <= i.id and vname = i.vname)
from ta a right join inserted i on i.id = a.id
go
insert ta select 'a',null
insert ta select 'a',null
insert ta select 'b',null
insert ta select 'a',null
insert ta select 'b',null
insert ta select 'a',null
select * from ta
drop table ta
/*
id vname num
----------- ---------- -----------
1 a 1
2 a 2
3 b 1
4 a 3
5 b 2
6 a 4
(所影响的行数为 6 行)
*/
create trigger tri_update_num
on tb
for insert
as
begin
update t1 set num=t2.num from tb t1 join (
select id,name,num=(select sum(num) from tb where name=t.name and id<=t.id) from tb t
)t2 on t1.id=t2.id
end