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.
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.
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
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:
Thanks again Matt for this opportunity to share an underrated, but really useful shiny new tool in SQL Server 2016.