利用触发器生成自增列

利用触发器生成自增列

--环境 
create table test_5 ( id int primary key not null, value int
--保存最大序列值的表 
create table Sequence ( rn int
insert Sequence select 0 
go 
create trigger tr_test_5 on test_5 
Instead of insert as 
begin 
  declare @n int 
  update Sequence set rn=rn+@@rowcount,@n=rn 
  insert test_5 
  select @n+row_number()over(order by getdate()),value from inserted 
end 
go
insert test_5(value) 
select 1 union 
select 2 union 
select 3 

select * from test_5 
/* 
id value 
----------- ----------- 
1 1 
2 2 
3 3
*/

你可能感兴趣的:(利用触发器生成自增列)