Wednesday, November 12, 2008

fn_Parse

the code is

CREATE FUNCTION fn_parse (@str varchar(255), @delim char(1), @token tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE @start tinyint
, @end tinyint
, @loopcnt tinyint

set @end = 0
set @loopcnt = 0
set @delim = substring(@delim, 1, 1)

-- loop to specific token
while (@loopcnt < @token) begin
set @start = @end + 1
set @loopcnt = @loopcnt + 1
set @end = charindex(@delim, @str+@delim, @start)
if @end = 0 break
end

if @end = 0
set @str = null
else
set @str = substring(@str, @start, @end-@start)

RETURN @str


source:http://www.sqlservercentral.com/scripts/Miscellaneous/30334/
END

No comments: