SQL查询将列数据拆分成行
我有SQL表中,我有2个字段为No
和declaration
Code Declaration 123 a1-2 nos, a2- 230 nos, a3 - 5nos
我需要显示该代码的声明为:
Code Declaration 123 a1 - 2nos 123 a2 - 230nos 123 a3 - 5nos
我需要将列数据拆分为该代码的行。
对于这种types的数据分离,我会build议创build一个分割函数:
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1)) returns @temptable TABLE (items varchar(MAX)) as begin declare @idx int declare @slice varchar(8000) 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) insert into @temptable(Items) values(@slice) set @String = right(@String,len(@String) - @idx) if len(@String) = 0 break end return end;
然后在查询中使用这个,你可以使用outer apply
来join你现有的表格:
select t1.code, s.items declaration from yourtable t1 outer apply dbo.split(t1.declaration, ',') s
这将产生结果:
| CODE | DECLARATION | ----------------------- | 123 | a1-2 nos | | 123 | a2- 230 nos | | 123 | a3 - 5nos |
看演示与SQL小提琴
或者你可以实现一个类似于这样的CTE版本:
;with cte (code, DeclarationItem, Declaration) as ( select Code, cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem, stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration from yourtable union all select code, cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem, stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration from cte where Declaration > '' ) select code, DeclarationItem from cte
Declare @t Table([Code] int, [Declaration] varchar(32)); Insert Into @t([Code], [Declaration]) Values(123, 'a1-2 nos, a2- 230 nos, a3 - 5nos') Select x.[Code] ,t.Declaration From ( Select *, Cast('<X>'+Replace(t.[Declaration],',','</X><X>')+'</X>' As XML) As record From @tt )x Cross Apply ( Select fdata.D.value('.','varchar(50)') As Declaration From x.record.nodes('X') As fdata(D) ) t
很less有时候,我已经在使用Set base方法在Sql Server中发布了相同的Splitfunction
另外,请访问Erland Sommarskog博客,他们保持了过去15年以来的相同答案。
尝试这个….
declare @col1 varchar(100),@CurentSubString varchar(100) create table #temp ( col1 varchar(50) ) DECLARE CUR CURSOR FOR SELECT col1 FROM your_table open CUR FETCH next FROM CUR INTO @col1 WHILE @@FETCH_STATUS = 0 BEGIN WHILE CHARINDEX (@col1, ';') <> 0 BEGIN SET @CurentSubString = SUBSTRING(@col1,1,CHARINDEX (@col1, ';')) SET @col1 = SUBSTRING(@col1,CHARINDEX (@col1, ';')+1,len(@col1)) insert into #temp select @CurentSubString END IF CHARINDEX (@col1, ';') = 0 and isnull(@col1,'')!= '' BEGIN INSERT INTO #temp SELECT @col1 END FETCH next FROM CUR INTO @col1 END select * From #temp CLOSE CUR DEALLOCATE CUR