--类似这个,自己写个函数实现自动编号--自动编号的例子.材料编号=类别编号+流水号--创建自定义函数,得到新的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 table tb(材料编号 varchar(7) primary key default '',类别编号 varchar(3),材料名称 varchar(10))
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材料'--显示结果
select * from tb order by 材料编号go
--删除测试环境
drop table tb
drop function f_getid