Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by two delimiters into two columns

Tags:

sql

sql-server

I have a string value which has numeric values separated by comma and then by a pipe. I want to split them into a table with two columns. I could split the string by one delimiter but unfortunately couldn't find a way to split by two. Please help.

DECLARE @list NVARCHAR(MAX) = '1,101|2,202|3,303';

The result should be like below.

1   101
2   202
3   303

Thanks in advance.

like image 948
Daybreaker Avatar asked Nov 08 '22 18:11

Daybreaker


1 Answers

If you're using SQL Server 2016 or Azure, you have access to the new SPLIT_STRING function. If not I recommend using Jeff Moden's DelimitedSplit8K function, which is widely regarded as the fastest, most efficient SQL based string splitter available...

DECLARE @list NVARCHAR(MAX) = '1,101|2,202|3,303';

SELECT 
    Col1 = LEFT(dsk.Item, sl.SplitLocation - 1),
    Col2 = SUBSTRING(dsk.Item, sl.SplitLocation + 1, LEN(dsk.Item))
FROM 
    dbo.DelimitedSplit8K(@list, '|') dsk    -- code for DelimitedSplit8K can be found here... http://www.sqlservercentral.com/articles/Tally+Table/72993/
    CROSS APPLY ( VALUES (ISNULL(NULLIF(CHARINDEX(',', dsk.Item, 1), 0), 1)) ) sl (SplitLocation);
like image 71
Jason A. Long Avatar answered Nov 14 '22 21:11

Jason A. Long