所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。
触发器问题,插入数据时,自动更新表的数据
http://bbs.csdn.net/topics/390634682
表1有字段1,字段2
插入数据4行
字段1 字段2
101
102
101
102
我想通过触发器,直接更新字段2,实现
字段1 字段2
101 101+1
102 102+1
101 101+2
102 102+2
这样的功能,请各位帮忙看看,如何来实现,
在插入数据的时候,实现更新。
方法1,适合2005及以后的版本:
- --drop table tb
-
- create table tb
- (字段1 int, 字段2 int, 字段3 int, 字段4 int)
-
-
- drop trigger trigger_tb
-
- create trigger dbo.trigger_tb
- on tb
- for insert
- as
-
- ;with t
- as
- (
- select tb.*,
- row_number() over(partition by tb.字段1 order by tb.字段4) as rownum
- from tb
- inner join inserted i
- on tb.字段1 = i.字段1
- and tb.字段3 = i.字段3
- and tb.字段4 = i.字段4
- )
-
- update t
- set 字段2 = 字段1+rownum
-
- go
-
-
- insert into tb
- select 101,null, 1, 1
- union all select 102,null, 1, 2
- union all select 101,null, 1, 3
- union all select 102,null, 1, 4
-
-
- --查询
- select *
- from tb
- /*
- 字段1 字段2 字段3 字段4
- 101 102 1 1
- 102 103 1 2
- 101 103 1 3
- 102 104 1 4
- */
- --drop table tb
-
- create table tb
- (字段1 int, 字段2 int, 字段3 int, 字段4 int)
-
-
- --drop trigger trigger_tb
-
- create trigger dbo.trigger_tb
- on tb
- for insert
- as
-
- update tb
- set 字段2 = t1.字段1 + (select count(*) from tb t2
- where t2.字段1 = t1.字段1
- and t2.字段4 <= t1.字段4)
- from tb t1
- inner join inserted i
- on t1.字段1 = i.字段1
- and t1.字段3 = i.字段3
- and t1.字段4 = i.字段4
-
- go
-
-
- insert into tb
- select 101,null, 1, 1
- union all select 102,null, 1, 2
- union all select 101,null, 1, 3
- union all select 102,null, 1, 4
-
-
- --查询
- select *
- from tb
- /*
- 字段1 字段2 字段3 字段4
- 101 102 1 1
- 102 103 1 2
- 101 103 1 3
- 102 104 1 4
- */
另一个例子,SQL Server2000触发器实现一个表的更新:
- --drop table mocta
-
- create table purtb
- (请购单号 varchar(10),参考单号 varchar(10),备注 varchar(50))
-
- create table mocta
- (工单单号 varchar(10),订单单号 varchar(10))
-
-
- insert into purtb
- select ‘101‘,‘201‘,‘301‘ union all
- select ‘102‘,‘302‘,‘302‘ union all
- select ‘103‘,‘备料‘,‘备料‘
-
- insert into mocta
- select ‘201‘,‘301‘ union all
- select ‘202‘,‘302‘
- go
-
- --drop trigger trigger_purtb_insert
-
-
-
- create trigger dbo.trigger_purtb_insert
- on purtb
- for insert
- as
-
- update purtb
- set 备注 = isnull((select t1.订单单号
- from mocta t1
- where i.参考单号 = t1.工单单号),
- i.参考单号)
- from inserted i
- where purtb.请购单号 = i.请购单号 and
- purtb.参考单号 = i.参考单号
-
-
- go
-
-
- insert into purtb(请购单号,参考单号)
- select ‘104‘,‘201‘
- union all select ‘105‘,‘xxx‘
-
-
-
-
- --查询
- select *
- from purtb
- /*
- 请购单号 参考单号 备注
- 101 201 301
- 102 302 301
- 103 备料 备料
- 104 201 301
- 105 xxx xxx
- */
在论坛中出现的比较难的sql问题:9(触发器专题 插入数据自动更新表数据)
原文:https://www.cnblogs.com/lonelyxmas/p/12019990.html