SQL 2005 Split Comma Separated Column on Delimiter

后端 未结 5 935
花落未央
花落未央 2020-12-09 22:44

My google searches on how to split a string on a delimiter have resulted in some useful functions for splitting strings when the string is known (i.e. see below):

         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 23:43

    alter procedure [dbo].[usp_split](@strings varchar(max)) as  
    begin  
        Declare @index int  
        set @index=1  
        declare @length int  
        set @length=len(@strings)  
        declare @str varchar(max)  
        declare @diff int  
        declare @Tags table(id varchar(30))  
        while(@index<@length)  
        begin  
            if(@index='1')  
            begin  
                set @str=(SELECT substring(@strings, @index, (charindex(',',(substring(@strings, @index,(@length)))))-1))  
                insert into @Tags values(@str)  
                    set @index=(charindex(',',(substring(@strings, @index,(@length)))))  
            end  
            else  
            begin  
                set @diff=@length-@index  
                if(@diff !=0)  
                begin  
                    set @str=(select substring(@strings, @index, (charindex(',',(substring(@strings,@index,@diff))))-1))  
                    if(@str is not null and @str!='')  
                    begin  
                        insert into @Tags VALUES(@str)  
                    end  
                    set @index=@index +(charindex(',',(substring(@strings, @index,@diff))))  
                end  
            end
        end
        set @str=(select right(@strings,(charindex(',',(substring(reverse(@strings),1,(@length)))))-1)) 
        insert into @Tags VALUES(@str)   
        select id from @Tags  
    end
    

    Usage:

    exec usp_split '1212,21213,1,3,133,1313131,1,231313,5'
    

提交回复
热议问题