表temp
no varchar(10)
115
120
121
124
125
126
129
......
如何能通过函数返回 115,120--121,124--126,129
就是不连续的单个取(用逗号分隔),连续的取首尾(用--号分隔)
no varchar(10)
115
120
121
124
125
126
129
......
如何能通过函数返回 115,120--121,124--126,129
就是不连续的单个取(用逗号分隔),连续的取首尾(用--号分隔)
create function fn_ToStr()
returns varchar(2000)
as
begin
declare @t1 table (id int IDENTITY(1,1),No varchar(10))
declare @t2 table (id int IDENTITY(1,1),No varchar(10))insert @T1(No)
select No from [temp] a
where not exists (
select 1 from [temp] where No=a.No-1
)insert @T2(No)
select No from [temp] a
where not exists (
select 1 from [temp] where No=a.No+1
)declare @r varchar(2000)
set @r=''
select @r=@r+','+case when t1.No=T2.No then t1.No
else T1.No+'--'+t2.No end
from @T1 t1,@t2 t2
where t1.id=t2.id
return stuff(@r,1,1,'')
end
go--调用
select dbo.fn_ToStr()--结果
-------------------------------------------------------------------------
115,120--121,124--126,129(所影响的行数为 1 行)
create table t(name varchar(5))
insert t select 115
insert t select 120
insert t select 121
insert t select 124
insert t select 125
insert t select 126
insert t select 129
goselect id=identity(int,1,1),a.name into #t1 from t a where not exists(select 1 from t where name=a.name-1)
select id=identity(int,1,1),a.name into #t2 from t a where not exists(select 1 from t where name=a.name+1)declare @sql varchar(8000)
set @sql=''
select @sql=@sql+c.st+'--'+c.ed+',' from (select st=a.name,ed=b.name from #t1 a,#t2 b where a.id=b.id and a.name<>b.name) c
set @sql=left(@sql,len(@sql)-1)
select @sql=@sql+','+c.st from (select st=a.name,ed=b.name from #t1 a,#t2 b where a.id=b.id and a.name=b.name) c
select @sql--删除测试数据
drop table t,#t1,#t2
/*结果
120--121,124--126,115,129
*/