MS SQL String Splits

SQL -

String to rows

Code

Using the useful function STRING_SPLIT(), we can convert a text to table rows: DECLARE @myvariable varchar(MAX) = 'a,b,c,d,e,f,g'; SELECT [value] FROM STRING_SPLIT(@myvariable, ',')

Result

This produces the following table:
value
1a
2b
3c
4d
5e
6f
7g

Concatenate rows

Setup

Let's say I have the following table: #myTable
NameCodePrice
1Alex1111
2Bob1212
3Alex1313
4Callum1414
5Bob1515
6Bob1616
7DanielNULL7
8Emily1818
9Daniel1919

Code

Using the useful function STRING_AGG(), we can concatenate rows to a single row: SELECT [Name], STRING_AGG([Code],'+') AS 'Codes', sum([Price]) AS 'TPrice' FROM #myTable GROUP BY [Name]

Result

This produces the following table:
NameCodesTPrice
1Alex111+1314
2Bob121+151+16113
3Callum1414
4Daniel19116
5Emily1818

Unconcatenate rows

Setup

Let's say I have the following table: #myTable
NameCodes
1Alex111+131
2Bob121+151+161
3Callum141
4DanielNULL
5Emily181
6Frank

Code - CROSS APPLY

Using the useful function STRING_SPLIT() from before, we can unconcatenate rows to multiple rows: SELECT [Name], value AS [Code] FROM #myTable CROSS APPLY STRING_SPLIT([Codes],'+');

Result

This produces the following table:
NameCode
1Alex111
2Alex131
3Bob121
4Bob151
5Bob161
6Callum141
7Emily181
8Frank

Code - OUTER APPLY

Using the useful function STRING_SPLIT() from before, we can unconcatenate rows to multiple rows: SELECT [Name], value AS [Code] FROM #myTable OUTER APPLY STRING_SPLIT([Codes],'+');

Result

This produces the following table:
NameCode
1Alex111
2Alex131
3Bob121
4Bob151
5Bob161
6Callum141
7DanielNULL
8Emily181
9Frank

CROSS APPLY vs OUTER APPLY

CROSS APPLY is like an inner join, only for rows that are non-null on both "tables".
OUTER APPLY is like left join, for all rows on left table.

Sources