sqlserver 查询出的数据做分割之后,进行排序

此方案对应的问题:

目前项目中存在着这样的编码:1, 1.1.1,1.1.1.1  2  2.1  2.1.1  .... 这样的数据,层级随意,深度随意。然后数据可以进行插入删除,之后要进行重新排序,目前只能按照编码进行排序,所以产生了如下的sql

 

 

-----分解函数
CREATE FUNCTION dbo.Split( @String varchar(8000),  @Delimiter char(1))
returns @temptable TABLE (items varchar(8000),splitLevel int )
as
begin
declare @idx int
declare @slice varchar(8000)
declare @index int 
set @index=0
select @idx=1
if len(@String)<1 or @String is null return

while @idx!=0
begin
set @idx=charindex(@Delimiter,@String)
if @idx!=0
set @slice=left(@String,@idx-1)
else
set @slice=@String

if(len(@slice)>0)
set @index=@index+1;
insert into @temptable(Items,splitLevel) values(@slice,@index)

set @String=right(@String,len(@String) -@idx)
if len(@String) =0     break
end
return
end
go


--创建临时表
create  table #test
( testid  varchar(30),
  splitValue varchar(300),
  sindex int
);
 
 insert into #test(testid,splitValue,sindex) values('1','1',1)
 insert into #test(testid,splitValue,sindex) values('1','1.1',1)
 insert into #test(testid,splitValue,sindex) values('1','2',1)
 insert into #test(testid,splitValue,sindex) values('1','2.1',1)
 insert into #test(testid,splitValue,sindex) values('1','2.1.2',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1.1',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1.1.1',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1.1.1.1',1)
 insert into #test(testid,splitValue,sindex) values('1','3.2.1.1',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1.2.1',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1.1.2',1)
 insert into #test(testid,splitValue,sindex) values('1','3.1.1.3',1)
 insert into #test(testid,splitValue,sindex) values('1','10',1)
 insert into #test(testid,splitValue,sindex) values('1','10.1',1)
  insert into #test(testid,splitValue,sindex) values('1','100.10',1)
---执行查询与分解
select items 'SalesOffice',splitLevel,testid,splitValue from #test   
CROSS apply dbo.split(#test.splitValue,'.')
--释放临时数据
drop  FUNCTION dbo.Split;
drop table #test;

 

posted @ 2022-09-30 16:09  keke..lele  阅读(292)  评论(0编辑  收藏  举报