Split Function in SQL


CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000) — List of delimited items
  , @sDelimiter VARCHAR(8000) = ‘,’ — delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList — Put the last item in
RETURN
END
GO

 

 

–Test
select * from fnSplit(’1,22,333,444,,5555,666′, ‘,’)
select * from fnSplit(’1##22#333##444′,’##’)  –note second item has embedded #
select * from fnSplit(’1 22 333 444  5555 666′, ‘ ‘)




by admin on May 5th, 2009 in Database
  1. KrisBelucci wrote on June 2nd, 2009 at 1:17 am Uhr1

    Hi, cool post. I have been wondering about this topic,so thanks for writing.

Name*: Website: E-Mail*:
XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>