tsql - SQL Split Function and Ordering Issue? -
i have following split
function,
alter function [dbo].[split](@string varchar(8000), @delimiter char(1)) returns @temptable table (items varchar(8000)) begin set @string = rtrim(ltrim(@string)) declare @idx int declare @slice varchar(8000) select @idx = 1 if len(@string)<1 or @string null return while @idx!= 0 begin set @idx = charindex(@delimiter,@string) if @idx!=0 set @slice = left(@string,@idx - 1) else set @slice = @string if(len(@slice)>0) insert @temptable(items) values(@slice) set @string = right(@string,len(@string) - @idx) if len(@string) = 0 break end return end
when write,
select items split('around home,clean , protect,soaps , air fresheners,air fresheners',',')
this give me,
air fresheners around home clean , protect soaps , air fresheners
i need maintain order.
a simpler function:
create function dbo.splitstrings_ordered ( @list nvarchar(max), @delimiter nvarchar(255) ) returns @t table([index] int identity(1,1), item nvarchar(255)) begin insert @t(item) select substring(@list, number, charindex(@delimiter, @list + @delimiter, number) - number) (select row_number() on (order [object_id]) sys.all_objects) n(number) number <= convert(int, len(@list)) , substring(@delimiter + @list, number, len(@delimiter)) = @delimiter order number option (maxdop 1); return; end go declare @s varchar(max) = 'around home,clean , protect,soaps , air' + ' fresheners,air fresheners'; select item dbo.splitstrings_ordered(@s, ',') order [index];
Comments
Post a Comment