Split Comma Separated Values in SQL Server

In this blog, I will show how to split comma separated values in SQL Server as a single value.
 
DECLARE @CommaSeparatedValues AS VARCHAR(500)
SET
@CommaSeparatedValues ='1,2,3,4,5,6,7,8,9,10'
DECLARE
@SplitData VARCHAR(64),
@start
INT,

@next
INT,

@last
INT

SELECT
@CommaSeparatedValues += ',',
@start
= 1,

@last
= LEN(@CommaSeparatedValues) + 1

WHILE
@last > @start
BEGIN

SET
@next = charindex(',', @CommaSeparatedValues, @start)

SET
@splitdata = RTRIM(LTRIM(SUBSTRING(@CommaSeparatedValues, @start, @next - @start)))

SET
@start = @next + 1

SELECT
@splitdata

END

The output of the above code is as follows: