gpt4 book ai didi

sql - SQL查询将列数据拆分为行

转载 作者:行者123 更新时间:2023-12-04 22:40:25 33 4
gpt4 key购买 nike

我有sql表,因为我有2个字段作为Nodeclaration

Code  Declaration
123 a1-2 nos, a2- 230 nos, a3 - 5nos

我需要将该代码的声明显示为:
Code  Declaration 
123 a1 - 2nos
123 a2 - 230nos
123 a3 - 5nos

我需要将列数据拆分为该代码的行。

最佳答案

对于这种类型的数据分离,我建议创建一个拆分函数:

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 |

参见 SQL Fiddle with Demo

或者,您可以实现类似于以下内容的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

关于sql - SQL查询将列数据拆分为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13527537/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com