Split string with delimitters

Hey guys,

I have got a function that will split the string considering the a string delimitted by the delimiters( comma , semicolan). The string might also contain spaces.
The first stage does not take space as Delimitter ... but in the other level we should consider tha space to be adelimitter .. how do we do it...

Ex:   I/p string is 'Best Buy,Dell,Office Max;ATT"

The final output should be

Best Buy
Office Max
Dell
ATT
Best
Buy
Office
Max

Please let me know how to do it...
split.txt
anjana_iAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AneeshDatabase ConsultantCommented:
create    FUNCTION [dbo].[fn_ParseString](
@OriginID nvarchar(4000))

RETURNS @tbl table (s varchar(1000))
as
/*
SELECT * from dbo.fn_ParseString ('1,2,0,6,7')
*/
BEGIN
      DECLARE @i int ,@j int
      SELECT       @i = 1
      WHILE @i <= len(@OriginID)
      BEGIN
            SELECT      @j = charindex(',', @OriginID, @i)
            if @j = 0
            BEGIN
                  SELECT      @j = len(@OriginID) + 1
            end
            INSERT      @tbl SELECT substring(@OriginID, @i, @j - @i)
            SELECT      @i = @j +1
      END
      RETURN
END

ThomasianCommented:
hi anjana_i,

Try
ALTER FUNCTION [dbo].[fnSplit] (
  @sInput varchar(8000),
  @Delimiter varchar(8000)=','
) RETURNS @List TABLE (Item varchar(8000))
AS
BEGIN
declare @s int, @e int
declare @Item varchar(8000)
 
set @s=1
set @e=1
WHILE @e>0
BEGIN
  set @e=CHARINDEX(@Delimiter,@sInput,@s+1)
  set @Item=SUBSTRING(@sInput,@s,CASE WHEN @e=0 THEN datalength(@sInput)+1 ELSE @e END -@s)
  INSERT INTO @List VALUES (@Item)
  IF CHARINDEX(' ',@Item)>0
  BEGIN
    INSERT INTO @List SELECT * FROM dbo.fnSplit(@Item,' ')
  END
  SET @s=@e+datalength(@delimiter)
END
 
RETURN
END
GO
 
SELECT * FROM dbo.fnSplit('Best Buy,Dell,Office Max,ATT',',')

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.