SQL Server 2016: The STRING_SPLIT Function

A long-awaited string function added to SQL Server 2016 is STRING_SPLIT. As the name implies, this function splits the given character expression using the separator set by user.

Let's see some examples of using the STRING_SPLIT function.

--Example #1
DECLARE @string AS VARCHAR(250);
SET @string = '1-2-3-4-5-6-7-8-9-10';

FROM STRING_SPLIT(@string, ',');


--Example #2
      id INT ,
      productsPurchased VARCHAR(250)

VALUES  ( 1, 'product1, product2, product3' );

SELECT  id ,
FROM    #test t
        CROSS APPLY STRING_SPLIT(productsPurchased, ',') t2;


--Example #3
CREATE TABLE #CSVHeaders ( headers VARCHAR(MAX) );

VALUES  ( 'header1,header2,header3,header4,header5,header6,header7,header8,header9,header10,header11,header12,header13,header14,header15' );

SELECT  LTRIM(value) AS HeaderName
FROM    #CSVHeaders
        CROSS APPLY STRING_SPLIT(headers, ','); 


As you can see, STRING_SPLIT is a very handy new string function in SQL Server 2016. It allows you to easily manipulate text and organize it by parsing it using separators.

For more info, please visit MSDN Books Online.

Reference: The SQL Server and .NET Hub (http://www.sqlnethub.com)

Labels: , ,