I am trying to make an SQL splitfunction which works reverse. Means
Input: 'Test1,Test2,Test3,Test4'
And the output should be:
| ID | Value |
| 1 | Test4 |
| 2 | Test3 |
| 3 | Test2 |
| 4 | Test1 |
I found a forwardworking function but I don't know what to change to make it work reversed. I have tried some stuff but it doesn't work.
Here is the original
CREATE FUNCTION [dbo].[SplitString]
(
@InputString VARCHAR(8000),
@Delimiter CHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(StartPos,Endpos)
AS(
SELECT 0 AS StartPos, CHARINDEX(@Delimiter,@InputString) AS Endpos
UNION ALL
SELECT Endpos+1, CHARINDEX(@Delimiter,@InputString,Endpos+1)
FROM Split
WHERE Endpos > 0
)
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Value' = SUBSTRING(@InputString,StartPos
,COALESCE(NULLIF(Endpos,0)
,LEN(@InputString)+1)-StartPos)
FROM Split
)
GO
with
SELECT ID, Value
FROM dbo.SplitString('Test1,Test2,Test3,Test4', ',');
you will get the output.