Dharmesh Sharma

Dharmesh Sharma

  • NA
  • 905
  • 926.5k

How to split string on spaces

Oct 8 2011 7:38 AM
hello

how to split the string in sql 
like
string -'this is new testing'
i want to like this
..................

this
is
new
testing

i m not get solution i m try my own code to do split its work for ", " but when i pass ' ' (space) its show error

Here is my code
ALTER FUNCTION [dbo].[Split_desc]
(
  -- Add the parameters for the function here
  @myString varchar(MAX),
  @deliminator varchar(10),
  @ID      INT
)
RETURNS
@ReturnTable TABLE
(
  -- Add the column definitions for the TABLE variable here
--  [id] [int] IDENTITY(1,1) NOT NULL,
  [part] [varchar](200) NULL,
  [ID]  [INT] Null
)
AS
BEGIN
  Declare @iSpaces int
  Declare @part varchar(50)

  --initialize spaces
  Select @iSpaces = charindex(@deliminator,@myString,0)
  While @iSpaces > 0

  Begin
  Select @part = substring(@myString,0,charindex(@deliminator,@myString,0))

  Insert Into @ReturnTable(part,id)
  Select @part,@id

  Select @myString = substring(@mystring,charindex(@deliminator,@myString,0)+ len(@deliminator),len(@myString) - charindex(' ',@myString,0))


  Select @iSpaces = charindex(@deliminator,@myString,0)
  end

  If len(@myString) > 0
  Insert Into @ReturnTable(part,id)
  Select @myString,@id

  RETURN
END

select * from [dbo].[Split_desc] ('dharmesh sharma',' ',11)

but its show errore

Msg 537, Level 16, State 5, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.


so plz help or give me some code

Answers (1)