sqlserver分隔字符串

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Get_StrOfIndex]'AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Get_StrOfIndex]
GO
Create function Get_StrOfIndex
(
@str varchar(1024),
@split varchar(10),
@index int
)
returns varchar(1024)
as
begin
    declare @location int
    declare @start int
    declare @next int
    declare @seed int
    set @str=ltrim(rtrim(@str))
    if substring(@str,0,len(@str)-1)<> @split
        set @str+=@split
    set @start=1
    set @next=1
    set @seed=len(@split)
    set @location=charindex(@split,@str)
    while @location<>0 and @index>@next
    begin
        set @start=@location+@seed
        set @location=charindex(@split,@str,@start)
        set @next=@next+1
    end
    --说明:这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号[已修复,最后一位,有无分隔符都可以]。
    if @location=0
        select @location=len(@str)+1
    return substring(@str,@start,@location-@start)
end
GO

---调用方法:select dbo.Get_StrOfIndex('8,9,3,3,4,5,',',',7)
--
-在数据中,无论最后,有没有分隔符号,都可以 
原文地址:https://www.cnblogs.com/wenming205/p/2398171.html