sql 逗号分隔转换成多行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 逗号分隔转换成多行相关的知识,希望对你有一定的参考价值。

	TRUNCATE TABLE LocationWithSourceId
	
	;WITH roy AS 
	(
	    SELECT LocationID,
	           SourceLocationID     = CAST(
	               LEFT(
	                   SourceLocationID,
	                   CHARINDEX(',', SourceLocationID + ',') -1
	               ) AS 
	               NVARCHAR(100)
	           ),
	           SPLIT                = CAST(
	               STUFF(
	                   SourceLocationID + ',',
	                   1,
	                   CHARINDEX(',', SourceLocationID + ','),
	                   ''
	               ) 
	               AS NVARCHAR(100)
	           )
	    FROM   (
	               SELECT LocationID,
	                      SourceLocationID
	               FROM   sf_Locations
	               WHERE  SourceLocationID LIKE '%,%'
	           ) k 
	    UNION ALL 
	    SELECT LocationID,
	           SourceLocationID     = CAST(LEFT(SPLIT, CHARINDEX(',', SPLIT) -1) AS NVARCHAR(100)),
	           SPLIT                = CAST(
	               STUFF(SPLIT, 1, CHARINDEX(',', SPLIT), '') AS NVARCHAR(100)
	           )
	    FROM   Roy
	    WHERE  SPLIT > ''
	)
	
	--SELECT * FROM roy
	
	INSERT LocationWithSourceId
	SELECT x.LocationID,
	       x.SourceLocationID
	FROM   roy x
	
	UNION ALL
	SELECT LocationID,
	       SourceLocationID
	FROM   sf_Locations
	WHERE  SourceLocationID NOT LIKE '%,%' AND SourceLocationID <> ''

以上是关于sql 逗号分隔转换成多行的主要内容,如果未能解决你的问题,请参考以下文章

SQL中逗号分隔的查询结果转换成单个字符串放到in语句里

使用 SQL Server 将逗号分隔的文本转换为多列结果

将单个逗号分隔的行转换为多行

将逗号分隔值转换为双引号逗号分隔字符串

sql一个字段内有分隔符如何拆分成多行

将多行字符串转换为单个逗号分隔