例如:
表 a:
tmh id
000055 2
000057 2
000059 2
000060 2
000061 2
000062 2
000063 2
000064 2
000065 3
000066 1
000600 1
要求得到如下结果:
tmh id
000055,000057,000059-000064 2
000065 3
000066,000600 1
将值相同的记录合并成一行,同时将连续的编号写成“起始编号-结束编号”的形式。
解决:
--☆子灵☆
--2009-09-23
create function tmhconvert(@id int)
returns varchar(2000)
as
begin
declare
@alltmh varchar(2000),--存放最后结果
@pretmh varchar(20),--前一个条码号
@flag bit,--0表示已经找到连续的,1表示没有。
@count int--用于判断是否运行到最后一条。
set @flag=1;
set @alltmh='';
select @count=count(*) from a where id=@id;
select @alltmh=@alltmh+case
when @pretmh is null then
tmh
when cast(@pretmh as int)+1=cast(tmh as int) then
case @count
when 1 then '-'+tmh
else ''
end
else
case @flag
when 0 then '-'+@pretmh+','+tmh
when 1 then ','+tmh
end
end,
@flag=case
when cast(@pretmh as int)+1=cast(tmh as int) then
0
else
1
end,
@pretmh=tmh,
@count=@count-1
from a where id=@id;
return @alltmh;
end