I have the following Split
function,
ALTER FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
set @String = RTRIM(LTRIM(@String))
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is 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 into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
When I write,
SELECT Items
FROM Split('around the home,clean and protect,soaps and air fresheners,air fresheners',',')
This will give me,
air fresheners
around the home
clean and protect
soaps and air fresheners
I need to maintain the order.
This will be a much faster solution when your string has 1000 or more values to split. For table-valued functions, to have any ordering, you must apply "ORDER BY" at the place of use. This is because "SELECT" from a table without "ORDER BY" is by convention not having any sorting.
Your function will need to set an order column (seq in this sample):
A simpler function:
Sample usage:
Or to return orders from a table ordered by input:
If you can abide compatibility level 130 of SQL Server, you can use the
String_Split()
function.With this and the Row_Number() function, you can return a table that includes the original sequence. For example:
Note that Row_Number requires an ordering, but if you pass a literal value the results are in the parsed sequence. This isn't guaranteed to be the case with future SQL Server version, as according to the String_Split documentation, there is no official ordering. I doubt Microsoft will break this, at least before introducing a version of the function that returns the order as it should, but in the mean time you best not depend on this ordering when writing code that decides whether or not to launch the missile.
Returns: