I am working on a SQL Server face problem which is splitting a string. I want to implement a function to split a string into an array:
Declare @SQL as varchar(4000)
Set @SQL='3454545,222,555'
Print @SQL
…what I have to do so I have an array in which I have:
total splitCounter=3
Arr(0)='3454545'
Arr(1)='222'
Arr(2)='555'
Below split function doesn't satisfy my need above, splitting a string into an array.
CREATE FUNCTION [dbo].[SplitString]
(
@String varchar(max)
, @Separator varchar(10)
)
RETURNS TABLE
AS RETURN
(
WITH
Split AS (
SELECT
LEFT(@String, CHARINDEX(@Separator, @String, 0) - 1) AS StringPart
, RIGHT(@String, LEN(@String) - CHARINDEX(@Separator, @String, 0)) AS RemainingString
UNION ALL
SELECT
CASE
WHEN CHARINDEX(@Separator, Split.RemainingString, 0) = 0 THEN Split.RemainingString
ELSE LEFT(Split.RemainingString, CHARINDEX(@Separator, Split.RemainingString, 0) - 1)
END AS StringPart
, CASE
WHEN CHARINDEX(@Separator, Split.RemainingString, 0) = 0 THEN ''
ELSE RIGHT(Split.RemainingString, LEN(Split.RemainingString) - CHARINDEX(@Separator, Split.RemainingString, 0))
END AS RemainingString
FROM
Split
WHERE
Split.RemainingString <> ''
)
SELECT
StringPart
FROM
Split
)
If you have any query please ask, thanks in advance. Any type of suggestion will be accepted.