SQL拆分字符串并获取NULL值而不是空字符串 [英] SQL split string and get NULL values instead of empty string
本文介绍了SQL拆分字符串并获取NULL值而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何拆分字符串并获取NULL值而不是空字符串.
How to split string and get NULL values instead of empty string.
我对 STRING_SPLIT
和 XML
两种方法特别感兴趣.我希望这个查询:
I am particularly interested in two methods STRING_SPLIT
and XML
.
I wish this query:
SELECT * FROM STRING_SPLIT('a,b,,d', ',');
将在第三行返回 NULL
而不是空字符串.有什么简单的方法可以实现它,即使用特殊字符?我的意思是:
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
我希望我可以使用 XML
方法从字符串中提取 NULL:
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));
从这里抓取的代码:https://sqlperformance.com/2016/03/t-sql-queries/string-split
推荐答案
用NULLIF
包裹返回值:
SELECT NULLIF([value],'') FROM STRING_SPLIT...
这篇关于SQL拆分字符串并获取NULL值而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文