Examples

A. Split comma-separated value string

Parse a comma-separated list of values and return all non-empty tokens.

DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'  
  
SELECT value  
FROM STRING_SPLIT(@tags, ',')  
WHERE RTRIM(value) <> '';

STRING_SPLIT will return empty string if there is nothing between separator. Condition RTRIM(value) <> ” will remove empty tokens.

B. Split comma-separated value string in a column

Product table has a column with comma-separate list of tags shown in the following example:

ProductIdNameTags
1Full-Finger Glovesclothing,road,touring,bike
2LL Headsetbike
3HL Mountain Framebike,mountain

Following query transforms each list of tags and joins them with the original row.

SELECT ProductId, Name, value  
FROM Product  
    CROSS APPLY STRING_SPLIT(Tags, ',');  

Here is the result set.

ProductIdNamevalue
1Full-Finger Glovesclothing
1Full-Finger Glovesroad
1Full-Finger Glovestouring
1Full-Finger Glovesbike
2LL Headsetbike
3HL Mountain Framebike
3HL Mountain Framemountain

More Examples:

SELECT DISTINCT 
	LTRIM(RTRIM(value)) AS Tag  
FROM 
	tblData 
	CROSS APPLY STRING_SPLIT(Tags, ',');  

Sources:

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017

Last modified: August 31, 2019

Author

Comments

Write a Reply or Comment