Przemyslaw Remin
Przemyslaw Remin

Reputation: 6940

SQL split string and get NULL values instead of empty string

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

Upvotes: 3

Views: 7646

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

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;

Upvotes: 3

Thom A
Thom A

Reputation: 95557

Wrap the returned value with NULLIF:

SELECT NULLIF([value],'') FROM STRING_SPLIT...

Upvotes: 16

Related Questions