我有sql表,因为我有两个字段No
和declaration
Code Declaration
123 a1-2 nos, a2- 230 nos, a3 - 5nos
我需要将该代码的声明显示为:
Code Declaration
123 a1 - 2nos
123 a2 - 230nos
123 a3 - 5nos
我需要将列数据拆分为该代码的行。
答案 0 :(得分:21)
对于这种类型的数据分离,我建议创建一个分割函数:
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
加入现有表:
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 |
或者您可以实现类似于此的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
答案 1 :(得分:5)
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 @t t
)x
Cross Apply
(
Select fdata.D.value('.','varchar(50)') As Declaration
From x.record.nodes('X') As fdata(D)
) t
几次回来,我在博客上写了同样的Split Function in Sql Server using Set base approach
此外,请访问自过去15年以来保持相同答案的Erland Sommarskog博客。
答案 2 :(得分:0)
试试这个......
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