How to split string and get NULL values instead of empty string.
I am particularly interested in two methods STRING_SPLIT
and XML
.
I wish this query:
SELECT * FROM STRING_SPLIT('a,b,,d', ',');
would return in third row NULL
instead of empty string.
Is there any easy way to achieve it i.e. with special characters? I mean something like:
SELECT * FROM STRING_SPLIT('a,b,[null],d', ',') -- this, of course, wouldn't go
I wish I could extract NULLs from string using XML
method:
CREATE FUNCTION dbo.SplitStrings_XML
(
@List varchar(8000),
@Delimiter char(1)
)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN (SELECT [value] = y.i.value('(./text())[1]', 'varchar(8000)')
FROM (SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>')
+ '</i>').query('.')
) AS a CROSS APPLY x.nodes('i') AS y(i));
Code grabbed from here: https://sqlperformance.com/2016/03/t-sql-queries/string-split