--创建自定义函数,得到新的ID
create function f_getid(
@类别编号 varchar(3))
returns int
as
begin
declare @re int
select @re=right(id,4) from(
select id=max(材料编号) from tb where 类别编号=@类别编号
) a
set @re=isnull(@re,0)+1
return(@re)
end
go
--创建触发器,自动生成材料编号
create trigger t_insert on tb
instead of insert
as
select * into #t from inserted order by 类别编号
declare @类别编号 varchar(3),@id int
update #t set @id=case when @类别编号=类别编号 then @id+1 else dbo.f_getid(类别编号) end
,材料编号=类别编号+right('0000'+cast(@id as varchar),4)
,@类别编号=类别编号
insert into tb select * from #t
go
--插入数据测试
insert into tb(类别编号,材料名称)
select '101','A材料'
union all select '101','B材料'
union all select '302','C材料'