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