SQL 中拆分由逗号分割的字段为多个字段

测试准备

创建表并填充数据

USE [zws]
GO
/****** Object:  Table [dbo].[a]    Script Date: 2018/5/3 16:28:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[a](
[barcode] [varchar](50) NULL,
[hardness] [varchar](50) NULL
) ON [PRIMARY]


GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[a] ([barcode], [hardness]) VALUES (N'20180503', N'14,12,11')
INSERT [dbo].[a] ([barcode], [hardness]) VALUES (N'20180502', N'11,12')
INSERT [dbo].[a] ([barcode], [hardness]) VALUES (N'20180501', N'10')
INSERT [dbo].[a] ([barcode], [hardness]) VALUES (N'20180504', N'11,12,13,14')
INSERT [dbo].[a] ([barcode], [hardness]) VALUES (N'20180505', N'11,12,13,14,15')

INSERT [dbo].[a] ([barcode], [hardness]) VALUES (N'2018050', NULL)


分割语句一:(该语句有问题,会过滤掉没有分隔符的数据)

 with s as(
 SELECT a.barcode,a.hardness+',' as 'hardness',CHARINDEX(',',a.hardness) as STA,CHARINDEX(',', a.hardness) - 1 AS LENS FROM dbo.a a
  UNION ALL
  SELECT 
    s.barcode,s.hardness, CHARINDEX(',',s.hardness, STA + 1) AS STA, CHARINDEX(',',s.hardness, STA + 1) - STA - 1 AS LENS
  FROM s AS s
  WHERE STA <> 0
 )


 select *,SUBSTRING(s.hardness,STA - LENS, LENS) as 'new_hardness'
 from s  
 where  STA<>0

 order by s.barcode,STA


分割语句二:

 with s as(
 SELECT a.barcode,a.hardness as 'hardness',CHARINDEX(',',a.hardness) as STA,CHARINDEX(',', a.hardness) - 1 AS LENS FROM dbo.a a
  UNION ALL
  SELECT 
    s.barcode,s.hardness, CHARINDEX(',',s.hardness, STA + 1) AS STA, CHARINDEX(',',s.hardness, STA + 1) - STA - 1 AS LENS
  FROM s AS s
  WHERE STA <> 0
 )


 select *,SUBSTRING(s.hardness,case when STA=0 then abs(LENS) else STA - LENS end, case when LENS<0 then abs(LENS)+10 else LENS end) as 'new_hardness'
 from s  


 order by s.barcode,case when STA=0 then abs(LENS) else STA  end


你可能感兴趣的:(SQL 中拆分由逗号分割的字段为多个字段)