3

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

Przemyslaw Remin
  • 6,276
  • 25
  • 113
  • 191

2 Answers2

16

Wrap the returned value with NULLIF:

SELECT NULLIF([value],'') FROM STRING_SPLIT...
Thom A
  • 88,727
  • 11
  • 45
  • 75
3

From what I can see, the value in between commas with nothing in between is actually showing up as empty string. So, you could use a CASE expression to replace empty string with NULL:

WITH cte AS (
    SELECT * FROM STRING_SPLIT('a,b,,d', ',')
)

SELECT
    value,
    CASE WHEN value = '' THEN NULL ELSE value END AS value_out
FROM cte;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360