To split comma separated string in SQL Server we need to write custom method for that we need to create one function like as shown below.
Custom Split function to split comma separated string into table,
- CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
- RETURNS @Results TABLE (Items nvarchar(4000))
- AS
- BEGIN
- DECLARE @INDEX INT
- DECLARE @SLICE nvarchar(4000)
-
-
- SELECT @INDEX = 1
- WHILE @INDEX !=0
- BEGIN
-
- SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-
- IF @INDEX !=0
- SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
- ELSE
- SELECT @SLICE = @STRING
-
- INSERT INTO @Results(Items) VALUES(@SLICE)
-
- SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-
- IF LEN(@STRING) = 0 BREAK
- END
- RETURN
- END
Once we create custom function Split() run sample query like as shown below,
- SELECT items FROM [dbo].[Split] ('861,739,10,1670', ',')
Once we run above query we will get output.