Friday, 13 March 2015

db_in_string parse delimited string

if exists (select * from information_schema.routines where routine_name = 'db_in_string' and routine_type= 'function') begin
    drop function [db_in_string]
end
go

create   function db_in_string (@p_string varchar(8000), @p_stop_value int, @p_sep_char varchar(2))
returns varchar(300) as

begin

declare @v_string varchar(8000),   
    @v_ctr numeric(3),
    @v_stop_value numeric(3),
    @v_comma_pos int,
    @v_string_len int,
    @v_sep_char varchar(2),
    @v_last_value varchar(8000),
    @v_return_value varchar(800)

-- if any of the values passed is null then return null
if (@p_string is null)
begin
    return(null)
end else begin
    set @v_string = @p_string
end
if (@p_stop_value is null)
begin
    return(null)
end else begin
    set @v_stop_value = @p_stop_value
end
if (@p_sep_char is null)
begin
    return(null)
end else begin
    set @v_sep_char = @p_sep_char
end

set @v_ctr = 1
-- get the length of the string passed in
set @v_string_len = len(@v_string)

if(substring(@v_string,len(@v_string),1)!= @p_sep_char) begin
  set @v_string = @v_string + @p_sep_char
end

-- loop through the string until value is at the beginning
while (@v_ctr < @v_stop_value)
begin
    set @v_string = substring(substring (@v_string, charindex( @v_sep_char, @v_string ),@v_string_len), 2, @v_string_len)
    set @v_ctr = @v_ctr + 1
end
set @v_last_value = @v_string
-- now get the position of the next ','
set @v_comma_pos = charindex(@v_sep_char, @v_string)

-- return the string
if (@v_comma_pos-1) < 0 begin
    set @v_return_value = @v_last_value
end else begin
    set @v_return_value = substring(@v_string,1, (@v_comma_pos-1))
    if @v_return_value = '' begin set @v_return_value = null end
end

return @v_return_value

end

go
set quoted_identifier off
go
set ansi_nulls on
go

No comments:

Post a Comment