I have a string in the database which is comma separated.Like 'apple,banana,pineapple,grapes' I need to split this string on the basis of comma and iterate through this.Since there is no built in function in sql server, Is there any efficient way in which this objective can be attained.
- 
                    What server side language are you using? – dev7 Jan 29 '14 at 10:45
4 Answers
Try this function
CREATE FUNCTION [dbo].[func_Split] 
    (   
    @DelimitedString    varchar(8000),
    @Delimiter              varchar(100) 
    )
RETURNS @tblArray TABLE
    (
    ElementID   int IDENTITY(1,1),  -- Array index
    Element     varchar(1000)               -- Array element contents
    )
AS
BEGIN
    -- Local Variable Declarations
    -- ---------------------------
    DECLARE @Index      smallint,
                    @Start      smallint,
                    @DelSize    smallint
    SET @DelSize = LEN(@Delimiter)
    -- Loop through source string and add elements to destination table array
    -- ----------------------------------------------------------------------
    WHILE LEN(@DelimitedString) > 0
    BEGIN
        SET @Index = CHARINDEX(@Delimiter, @DelimitedString)
        IF @Index = 0
            BEGIN
                INSERT INTO
                    @tblArray 
                    (Element)
                VALUES
                    (LTRIM(RTRIM(@DelimitedString)))
                BREAK
            END
        ELSE
            BEGIN
                INSERT INTO
                    @tblArray 
                    (Element)
                VALUES
                    (LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))
                SET @Start = @Index + @DelSize
                SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)
            END
    END
    RETURN
END
Example Usage – simply pass the function the comma delimited string as well as your required delimiter.
DECLARE @SQLStr varchar(100)
SELECT @SQLStr = 'Mickey Mouse, Goofy, Donald Duck, Pluto, Minnie Mouse'
SELECT
    *
FROM
    dbo.func_split(@SQLStr, ',')
Result will be like this

 
    
    - 27,863
- 13
- 63
- 115
- 
                    2I would use `SET @DelSize = LEN(@Delimiter + 'x') - 1` to handle delimiters with trailing blanks such as `' '` and `', '`. – Chry Cheng Jun 07 '16 at 09:25
- 
                    
- 
                    @ChryCheng - That is definitely something that should be included in this solution. – callisto Jun 20 '19 at 12:04
- 
                    I know this is fairly old - but thanks nonetheless. The only issue I have is when the substrings have embedded escaped delimiter, e.g. "Mickey\,Mouse, Goofy..." - this would split "Mickey\" and "Mouse" into two - but should only give me "Mickey,Mouse" as one – Aleks G Feb 04 '22 at 13:25
... Since there is no built in function in sql server ...
That was true at the time you asked this question but SQL Server 2016 introduces STRING_SPLIT.
So you can just use
SELECT value
FROM   STRING_SPLIT ('apple,banana,pineapple,grapes', ',') 
There are some limitations (only single character delimiters accepted and a lack of any column indicating the split index being the most eye catching). The various restrictions and some promising results of performance testing are in this blog post by Aaron Bertrand.
 
    
    - 438,706
- 87
- 741
- 845
You can convert your data to XML, by replacing the comma by a custom tag, in this case, <w> for word.
create table t(col varchar(255));
insert into t values ('apple,banana,pineapple,grapes');
insert into t values ('car,bike,airplane');
select cast(('<w>' + replace(col, ',', '</w><w>') + '</w>') as xml) as xmlValue
  from t
Which returns
|                                               XMLVALUE |
|--------------------------------------------------------|
| <w>apple</w><w>banana</w><w>pineapple</w><w>grapes</w> |
|                   <w>car</w><w>bike</w><w>airplane</w> |
Now, if you use this query as a inner xml select, the outer query can split it into distinct rows:
Solution:
select split.xmlTable.value('.', 'varchar(255)') as xmlValue
from (
   select cast(('<w>' + replace(col, ',', '</w><w>') + '</w>') as xml) as xmlValue
     from t
) as xmlTable
cross apply xmlValue.nodes ('/w') as split(xmlTable);
 
    
    - 15,009
- 9
- 58
- 71
I have a solution using Recursion as follows
Create function split_string(@str as nvarchar(max),@separator as char(1)) returns @myvalues Table (id int identity(1,1),myval nvarchar(100))
as 
--Kamel Gazzah
--23/04/2019
begin
with cte as(
select @str [mystr],
cast(1 as int) [Start],
charindex(@separator,@str)as Nd
union all
select substring(@str,nd+1,len(@str)),cast(Nd+1 as int),charindex(@separator,@str,Nd+1) from cte
where nd>0
)
insert into @myvalues(myval) 
select case when nd>0 then substring(@str,start,Nd-start) 
else substring(@str,start,len(@str)) end [splitted] 
from cte   OPTION (MAXRECURSION 1000);
return ;
end;
You can call this function
select * from split_string('apple,banana,pineapple,grapes',',')
 
    
    - 967
- 6
- 15
