create function getstrofindex (@str varchar(8000),@index int =0)
returns varchar(8000)
as
begin
  declare @str_return varchar(8000)
  declare @start int
  declare @next int
  declare @location int
  select @start =1
  select @next =1
  select @location = charindex('|||',@str,@start)
  while (@location <>0 and @index > @next )
  begin
    select @start = @location +1
    select @location = charindex('|||',@str,@start)
    select @next =@next +1
  end
  if @location =0 select @location =len(@str)+1 
  select @str_return = substring(@str,@start,@location -@start)
  if (@index <> @next ) select @str_return = '' 
  return @str_return
end
go
----调用:
select dbo.getstrofindex('a|||b|||c|||d|||e',3)

解决方案 »

  1.   

    谢谢,但有个小问题。
    如果用“select dbo.getstrofindex('a|||b|||c|||d|||e',3)”
    则返回“||c”
    而“select dbo.getstrofindex('a|||b|||c|||d|||e',1)”,没有问题,返回"a"
      

  2.   

    问题已经解决,要修改“select @start = @location +1”改成“select @start =@location +3”
      

  3.   

    create function getstrofindex (@str varchar(8000),@index int =0)
    returns varchar(8000)
    as
    begin
      declare @str_return varchar(8000)
      declare @start int
      declare @next int
      declare @location int
      select @start =1
      select @next =1
      select @location = charindex('|||',@str,@start)
      while (@location <>0 and @index > @next )
      begin
        select @start = @location +1
        select @location = charindex('|||',@str,@start)
        select @next =@next +1
      end
      select @location =len(@str)+1 where @location =0
      select @str_return = substring(@str,@start+2,@location -@start-2)
      if (@index <> @next ) select @str_return = '' 
      return @str_return
    end
    go
    ----调用:
    select dbo.getstrofindex('a|||b|||c|||d|||e',5)godrop function getstrofindex
      

  4.   

    楼上的,这个过程调用是select dbo.getstrofindex('a|||b|||c|||d|||e',1)出错。