I know there are a lot of solutions to this on the internet, here’s mine!
Sample use-cases:
Code:
CREATE FUNCTION [dbo].[Split](@list NTEXT ,@Delim CHAR(1) = ',')RETURNS @tbl TABLE(items VARCHAR(4000) NOT NULL)ASBEGINDECLARE @pos INT ,@textpos INT ,@chunklen SMALLINT ,@str NVARCHAR(4000) ,@tmpstr NVARCHAR(4000) ,@leftover NVARCHAR(4000)IF @Delim IS NULLBEGININSERT INTO @tbl( items )VALUES ( CAST(@list AS VARCHAR) -- items - varchar(4000))RETURNENDSET @textpos = 1SET @leftover = ''WHILE @textpos <= DATALENGTH(@list) / 2BEGINSET @chunklen = 4000 - DATALENGTH(@leftover) / 2SET @tmpstr = LTRIM(@leftover + SUBSTRING(@list, @textpos,@chunklen))SET @textpos = @textpos + @chunklenSET @pos = CHARINDEX(@Delim, @tmpstr)WHILE @pos > 0BEGINSET @str = SUBSTRING(@tmpstr, 1, @pos - 1)IF LTRIM(RTRIM(@str)) <> ''INSERT @tbl( items )VALUES ( @str )SET @tmpstr = LTRIM(SUBSTRING(@tmpstr, @pos + 1,LEN(@tmpstr)))SET @pos = CHARINDEX(@Delim, @tmpstr)ENDSET @leftover = @tmpstrENDIF LTRIM(RTRIM(@leftover)) <> ''INSERT @tbl( items )VALUES ( @leftover )RETURNEND
ReplyDeleteWonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!
ASC Coding