在论坛中出现的比较难的sql问题:9(触发器专题 插入数据自动更新表数据)

来源:互联网 发布:慢走丝统盈编程 编辑:程序博客网 时间:2024/05/21 23:24
最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。


触发器问题,插入数据时,自动更新表的数据

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 tbcreate table tb(字段1 int,   字段2 int,  字段3 int,  字段4 int)drop trigger trigger_tbcreate trigger dbo.trigger_tbon tbfor insertas;with tas(select tb.*,       row_number() over(partition by tb.字段1 order by tb.字段4) as rownumfrom tb inner join inserted i        on tb.字段1 = i.字段1           and tb.字段3 = i.字段3           and tb.字段4 = i.字段4)update tset 字段2 = 字段1+rownumgoinsert into tbselect 101,null,            1,      1union all select 102,null,  1,      2union all select 101,null,  1,      3union all select 102,null,  1,      4--查询select *from tb/*字段1字段2字段3字段4101    102    1    1102    103    1    2101    103    1    3102    104    1    4*/

方法2,适合2000:

--drop table tbcreate table tb(字段1 int,   字段2 int,  字段3 int,  字段4 int)--drop trigger trigger_tbcreate trigger dbo.trigger_tbon tbfor insertasupdate tbset 字段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.字段4goinsert into tbselect 101,null,            1,      1union all select 102,null,  1,      2union all select 101,null,  1,      3union all select 102,null,  1,      4--查询select *from tb/*字段1字段2字段3字段4101    102    1    1102    103    1    2101    103    1    3102    104    1    4*/


另一个例子,SQL Server2000触发器实现一个表的更新:

--drop table moctacreate table purtb(请购单号 varchar(10),参考单号 varchar(10),备注 varchar(50))create table mocta(工单单号 varchar(10),订单单号 varchar(10))insert into purtbselect '101','201','301' union allselect '102','302','302' union allselect '103','备料','备料'insert into moctaselect '201','301' union allselect '202','302'go--drop trigger trigger_purtb_insertcreate trigger dbo.trigger_purtb_inserton purtbfor insertasupdate purtbset 备注 = isnull((select t1.订单单号                   from mocta t1                    where i.参考单号 = t1.工单单号),                  i.参考单号)from inserted iwhere purtb.请购单号 = i.请购单号 and                  purtb.参考单号 = i.参考单号          goinsert into purtb(请购单号,参考单号)select '104','201'union all select '105','xxx'--查询select *from purtb/*请购单号参考单号备注101    201    301102    302    301103    备料    备料104    201    301105    xxx    xxx*/