我tbuser表里有字段id,username,password,groups(char 3),id是自增字段。
现在我想插入一条数据时(只知道username和password),groups的数据是根据当前插入数据的id来决定。
比如我当前插入的行id=1,那么groups就是010,id=2,groups就是020.该如何实现这个groups的取值。

解决方案 »

  1.   

    这个不如在建表达时候设置好groups as '0'+ltrim(id)+'0'
      

  2.   

    参考这种实现方式:
    declare @t table(id int identity,col int,gro as right('000'+ltrim(id),3))
    insert @t select 2 union all select 3select * from @t
    /*
    id          col         gro    
    ----------- ----------- ------ 
    1           2           001
    2           3           002(所影响的行数为 2 行)
    */
      

  3.   

    上次看tony哥写过的,又 忘了。晕
      

  4.   

    if object_id('tbuser') is not null drop table tbuser
      go
    create table tbuser(id int identity(1,1),username nvarchar(20),password nvarchar(200),groups char(3))
     go
    insert tbuser(username,password) 
      select '张三', hashbytes('MD5', '12345') 
      union all select '李四', hashbytes('MD5', '123') 
      union all select '王五', hashbytes('MD5', 'abc') 
    create trigger trigg_tb on dbo.tbuser
    for insert,update
    as
    update a set a.groups=cast(right(100+b.id,2) as varchar)+'0'  from dbo.tbuser a,inserted b where a.id=b.idselect * from tbuser
    /*
    id username password groups
    1 张三 粂໋諪汰㑌梡筎 010
    2 李四 Ⱐ抹妬嬇䮖ᔇ⌭灋 020
    3 王五 Ɛ顐툼끏雖紿牿 030
    */注意先建表,再建触发器,再插入数据,hashbytes在2000中不能用