Using STRING_SPLIT()
means, that you are working on SQL Server 2016 (oder higher).
However, STRING_SPLIT()
has a huge draw back: It is not guaranteed to return the items in the expected order (see the docs, section "Remarks"). In my eyes this is an absolut show stopper...
But - luckily - there is a fast and easy-to-use workaround in v2016+:
Create table #temp(Sid int,roleid varchar(100))
Insert into #temp values(500,'1,5,'),(501,'1,5,6,');
SELECT t.[Sid]
,A.[key] AS position
,A.[value] AS roleid
FROM #temp t
CROSS APPLY OPENJSON(CONCAT('["',REPLACE(t.roleid,',','","'),'"]')) A
WHERE A.[value]<>'';
A simple number array 1,3,5
needs nothing more than brackets to be a JSON array ([1,3,5]
). In your case, due to the trailing comma, I deal with it as strings. 1,3,5,
will be taken as array of strings: ["1","3","5",""]
. The final empty string is taken away by the WHERE clause. The rest is easy...
Other than STRING_SPLIT()
the docs proof, that OPENJSON
will reflect an item's position in the [key]
column:
When OPENJSON parses a JSON array, the function returns the indexes of the elements in the JSON text as keys.
General hint: avoid STRING_SPLIT()
as lons as there is no additional key/position column added to its result set.