select left(单号,2) + cast((right(a.单号,4)-1) as varchar) 单号 from table a
where not exists (select 1 from table where right(单号,4)=right(a.单号,4)-1)
order by 单号
--测试表
create table 表(单号 varchar(10))
insert into 表
select 'WL0001'
union all select 'WL0002'
union all select 'WL0004'
union all select 'RP0001'
union all select 'RP0002'
union all select 'RP0003'
union all select 'RP0006'
go
--得到编号缺号的字符列表
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getNseries]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_getNseries]
GO
create function f_getNseries(@head varchar(10))
returns varchar(8000)
as
begin
declare @re varchar(8000),@id int,@h varchar(10)
select @re='',@id=0,@h=@head+'%'
select @re=case @id when id-1 then @re
else @re+','+@head+right('0000'+cast(@id+1 as varchar),4)
+case @id+1 when id-1 then ''
else '-'+@head+right('0000'+cast(id-1 as varchar),4) end
end
,@id=id
from (select id=cast(right(单号,4) as int) from 表 where 单号 like @h) a
set @re=substring(@re,2,8000)
return(@re)
end
go
--调用实现你的要求
select dbo.f_getNseries(aa) from(
select distinct aa=left(单号,2) from 表
) a
--函数再改一下:
--得到编号缺号的字符列表
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getNseries]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_getNseries]
GO
create function f_getNseries(@head varchar(10))
returns varchar(8000)
as
begin
declare @re varchar(8000),@id int,@h varchar(10)
select @re='',@id=0,@h=@head+'%'
select @re=case @id when id-1 then @re
else @re+','+@head+right('0000'+cast(@id+1 as varchar),4)
+case @id+1 when id-1 then ''
else '-'+@head+right('0000'+cast(id-1 as varchar),4) end
end
,@id=id
from (select id=cast(right(单号,4) as int) from 表 where 单号 like @h) a
set @re=substring(@re,2,8000)
return(@re)
end
go
--得到编号缺号的字符列表
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getNseries]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_getNseries]
GO
create function f_getNseries(@head varchar(10))
returns varchar(8000)
as
begin
declare @re varchar(8000),@id int
select @re='',@id=0,@head=@head+'%'
select @re=case @id when id-1 then @re
else @re+','+cast(@id+1 as varchar)
+case @id+1 when id-1 then ''
else '-'+cast(id-1 as varchar) end
end
,@id=id
from (select id=cast(right(单号,4) as int) from 表 where 单号 like @head) a
set @re=substring(@re,2,8000)
return(@re)
end
go
--调用实现你的要求
select dbo.f_getNseries(aa) from(
select distinct aa=left(单号,2) from 表
) a