SQL split string and get NULL values instead of empty string

社会主义新天地 提交于 2019-12-11 06:13:00

问题


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


回答1:


Wrap the returned value with NULLIF:

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



回答2:


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;


来源:https://stackoverflow.com/questions/54422666/sql-split-string-and-get-null-values-instead-of-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!