一级(2位),二级以后占用(3位),比如一级:01或02,二级:01001或01003,那三级编号就是01001001或01111112,我就写了一个存储过程【个人测试没问题,可以参考一下】获取即将要添加的编号(模拟场景:选择权限的树状图节点添加子集节点,需要计算出子集节点的将要插入的id)
ALTER PROCEDURE [dbo].[GetMaxId]
(
@tablename nvarchar(100),--表名
@idcol nvarchar(100),--列名
@parent nvarchar(100),--父级编号
@jb int,--级别
@ids nvarchar(50) output--最终的id
)
AS
BEGIN
declare @str nvarchar(2000)
set @str=''
--一级添加
if @jb=1
begin
set @str=@str+'select @ids=cast(max(
'+@idcol+'
) as int)+1 from
'+@tablename+'
where len(
'+@idcol+')<=2
'
exec sp_executesql @str,N'@ids nvarchar(50) output',@ids output
if(len(@ids) is null)
set @ids='01'
else IF(len(@ids)<=2)
set @ids='0'+@ids
end
else
begin
set @str=@str+'select @ids=CAST(max(RIGHT(
'+@idcol+',3))as
int)+1 from
'+@tablename+'
where len(
'+@idcol+')=2+('+CAST
(
@jb as nvarchar(20)) +'-1)*3 and
'+@idcol+'
like
'''+@parent+'%'''
exec sp_executesql @str,N'@ids nvarchar(50) output',@ids output
IF(len(@ids)=1)
set @ids='00'+@ids
else IF(len(@ids)=2)
set @ids='0'+@ids
else if(len(@ids) is null)
set @ids='001'
IF @parent<>'' and @parent is not null
SET @ids=@parent+@ids
end
END