Sunday, April 30, 2006

Split in SQL

Split list of numbers ('1, 2, 3, 4, 67, 87') to table.

Input: : List of numbers (0;1;5;45;...)

Ouput:

0 1545...

A using: SELECT * FROM Split('0;1;5;45;',';')

CREATE FUNCTION Split
(

@list varchar(8000), -- List of integer with any delemiter

@delimiter CHAR(1) -- Delimetr

)
RETURNS
@list_int TABLE (item int) --list of integer

AS
   BEGIN
  DECLARE @position int, @itemvarchar(20)

   WHILE @list <> ''
   BEGIN
     SET @position = CHARINDEX(@delimiter, @list)
     IF @position = 0
     SET @position = LEN(@list) + 1

     SET @item=LEFT(@list, @position - 1)
     INSERT INTO @list_int VALUES(CAST(@itemAS int))
     SET @list = STUFF(@list, 1, @position, '')
    END
RETURN
END

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.