I have a need to create a function the will return nth element of a delimited string.
For a data migration project, I am converting JSON audit records stored in a S
In a rare moment of lunacy I just thought that split is far easier if we use XML to parse it out for us:
(Using the variables from @Gary Kindel's answer)
declare @xml xml
set @xml = '' + replace(@list,@Delimiter,' ') + ' '
select
el = split.el.value('.','varchar(max)')
from @xml.nodes('/split/el') split(el))
This lists all elements of the string, split by the specified character.
We can use an xpath test to filter out empty values, and a further xpath test to restrict this to the element we're interested in. In full Gary's function becomes:
alter FUNCTION dbo.GetSplitString_CTE
(
@List VARCHAR(MAX),
@Delimiter VARCHAR(255),
@ElementNumber int
)
RETURNS VARCHAR(max)
AS
BEGIN
-- escape any XML https://dba.stackexchange.com/a/143140/65992
set @list = convert(VARCHAR(MAX),(select @list for xml path(''), type));
declare @xml xml
set @xml = '' + replace(@list,@Delimiter,' ') + ' '
declare @ret varchar(max)
set @ret = (select
el = split.el.value('.','varchar(max)')
from @xml.nodes('/split/el[string-length(.)>0][position() = sql:variable("@elementnumber")]') split(el))
return @ret
END