我的一个表a如下:ID       名称         上级ID       编码
                 1        第一个                     01
                 2        第二个         1           0102
                 3        第三个         1           0103
                 4        第四个         3           010301比如当编码为“0103”时,他的“上级ID”就是“第一个”的“ID”,因为“第三个”的“编码”可以算是“第一个”的“编码”的下一节。  “第四个”的“上级ID”就是“第三个”的“ID”当往表a中插入数据时,只会插入“名称”和“编码”
insert into a(名称,编码) values ('第五个','010302')
我想通过触发器能够将新插入的记录的“上级ID”赋值上一节的“ID”,请问这个触发器应该如何写呢?
谢谢!!

解决方案 »

  1.   

    /*====================================================*/
    -- Author: Ken Wong
    -- Create date: 2009-12-22 15:33:01
    -- Description:
    /*====================================================*/
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    create table [tb]([ID] int identity(1,1),[名称] varchar(6),[上级ID] varchar(2),[编码] varchar(6))
    insert [tb]
    select '第一个','','01' union all
    select '第二个','1','0102' union all
    select '第三个','1','0103' union all
    select '第四个','3','010301'create trigger insertid on [tb]
    for insert
    as
    begin
    declare @code varchar(20)
    select @code = [编码] from inserted
    update [tb] set [上级ID] = cast(right(left(@code,len(@code)-2),2) as int)
    where id = @@identityendinsert into [tb](名称,编码) values ('第五个','010302') select * from [tb]
    ---------------------
    1 第一个 01
    2 第二个 1 0102
    3 第三个 1 0103
    4 第四个 3 010301
    5 第五个 3 010302
      

  2.   

    create table tb (id int identity(1,1),名称 nvarchar(10),上级id int,编码 nvarchar(10))
    insert into tb(名称,上级id,编码)select '第一个','','01'
        union all  select '第二个',1,'0102'
        union all  select '第三个',1,'0103'
        union all  select '第四个',3,'010301'
    go
    create trigger tri_g on tb 
    after insert 
    as 
    begin
      update a set a.上级id= (select max(id) from tb where b.编码 like 编码+'%' and id<>b.id) from tb a join inserted b on a.id=b.id
    end
    goinsert into tb (名称,编码) select '第五个','010302'select * from tb
    go
    drop table tb
    go
    if object_id('tri_g')is not null
        drop trigger tri_g
    /*
    (4 行受影响)(1 行受影响)(1 行受影响)
    id          名称         上级id        编码
    ----------- ---------- ----------- ----------
    1           第一个        0           01
    2           第二个        1           0102
    3           第三个        1           0103
    4           第四个        3           010301
    5           第五个        3           010302(5 行受影响)
    */