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:
ProductId | Name | Tags |
---|---|---|
1 | Full-Finger Gloves | clothing,road,touring,bike |
2 | LL Headset | bike |
3 | HL Mountain Frame | bike,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.
ProductId | Name | value |
---|---|---|
1 | Full-Finger Gloves | clothing |
1 | Full-Finger Gloves | road |
1 | Full-Finger Gloves | touring |
1 | Full-Finger Gloves | bike |
2 | LL Headset | bike |
3 | HL Mountain Frame | bike |
3 | HL Mountain Frame | mountain |
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
Comments