ALTER function [dbo].[StrToList_Test](@Str varchar(max), @fg NVARCHAR(200))returns @table table( value nvarchar(max))asbegindeclare @tempStr nvarchar(max),@len INT = LEN(@fg);--去除前后分割符while substring(@Str,1,@len)=@fgbegin set @Str=substring(@Str,@len+1,len(@Str))endwhile RIGHT(@Str,@len)=@fgbegin set @Str=substring(@Str,1,len(@Str)-@len)endif(len(@Str)>0)begin while(charindex(@fg,@Str)>0) begin set @tempStr=substring(@Str,1,charindex(@fg,@Str)-1) insert into @table(value) values(@tempStr) set @Str=substring(@Str,charindex(@fg,@Str)+@len,len(@Str)) end insert into @table(value) values(@Str) --没有分割符保存值endreturnend
调用如:select * from [dbo].[StrToList_Test]('ab||cd||ef||ghi||jg','||')