Thanks to Matt Gordon (@atsqlspeed) for hosting this T-SQL Tuesday.
Splitting Strings in SQL
A problem that has plagued SQL developers through the years is splitting strings. Many techniques have been used as more capabilities were added to SQL Server including XML datatypes, recursive CTEs and even CLR. I have used XML datatype methods to solve the problem most often. So, without further ado…
T-SQL Function: STRING_SPLIT
I have previously highlighted this function in a webinar with Pragmatic Works as a Hidden Gem in SQL Server 2016. It was not announced with great fanfare, but once discovered, solves a very common problem.
Syntax
STRING_SPLIT(string, delimiter)
The STRING_SPLIT function will return a single column result set. The column name is “value”. The datatype will be NVARCHAR for strings that are NCHAR or NVARCHAR. VARCHAR is used for strings that are CHAR or VARCHAR types.
Example
DECLARE @csvString AS VARCHAR(100) SET @csvString = 'Monday, Tuesday, Wednesday, Thursday, Friday' SELECT value AS WorkDayOfTheWeek FROM STRING_SPLIT (@csvString, ',');
The initial example returns the follow results:#tsql2sday
value |
---|
Monday |
Tuesday |
Wednesday |
Thursday |
Friday |
As you can see in the example, the results returned a leading space which was in the original string. The following example trims leading and trailing spaces.
DECLARE @csvString AS VARCHAR(100) SET @csvString = 'Monday, Tuesday, Wednesday, Thursday, Friday' SELECT LTRIM(RTRIM(value)) AS WorkDayOfTheWeek FROM STRING_SPLIT (@csvString, ',');
The cleaned example returns the follow results:
value |
---|
Monday |
Tuesday |
Wednesday |
Thursday |
Friday |
Thanks again Matt for this opportunity to share an underrated, but really useful shiny new tool in SQL Server 2016.