在 XML 变量中用 NULL 替换空字符串

Replace empty string with NULL in XML variable(在 XML 变量中用 NULL 替换空字符串)
本文介绍了在 XML 变量中用 NULL 替换空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个查询返回 NULL 而不是空字符串.

I wish this query would return NULL instead of empty string.

declare @str varchar(max)='A,,C;D,E,F;X,Y,Z'; -- please notice missing B
declare @xmlstr XML
set @xmlstr = CAST(('<rows><row><col>' + REPLACE(REPLACE(@str,';','</col></row><row><col>'),',','</col><col>') + '</col></row></rows>') AS XML)

SELECT
     t.n.value('col[1]','nvarchar(max)') as Col1
    ,t.n.value('col[2]','nvarchar(max)') as Col2
    ,t.n.value('col[3]','nvarchar(max)') as Col3
FROM
    @xmlstr.nodes ('/rows/row') AS t(n)

这个例子来自https://stackoverflow.com/a/39752683/1903793

来自答案:SQL拆分字符串并获得 NULL 值而不是空字符串 我知道它可以通过使用 NULLIF 函数轻松包装来修复:

From the answer: SQL split string and get NULL values instead of empty string I know it can be fixed by easy wrap with NULLIF function:

SELECT
     nullif(t.n.value('col[1]','nvarchar(max)'),'') as Col1
    ,nullif(t.n.value('col[2]','nvarchar(max)'),'') as Col2
    ,nullif(t.n.value('col[3]','nvarchar(max)'),'') as Col3

但是我想知道它是否可以通过直接使用 XML 变量 进行操作来修复,而不是之后进行操作.

However I wonder if it might be alternatively fixed by manipulating with XML variable directly, not afterwards.

注意.我的问题遵循 SQL 拆分字符串并获取 NULL 值而不是空字符串请不要将其标记为欺骗,因为我还没有收到 XML 方法的答案.

Note. My question follows SQL split string and get NULL values instead of empty string Please do not mark it as dupe because I have not received answer for XML method.

推荐答案

此答案的功劳完全归功于 Jeroen Mostert.详情请看他的评论.

The credit for this answer is entirely to Jeroen Mostert. For details please see his comments.

declare @str varchar(max)='A,,C;D,E,F;X,Y,Z'; -- please notice missing B
declare @xmlstr XML
set @xmlstr = CAST(('<rows><row><col>' + REPLACE(REPLACE(@str,';','</col></row><row><col>'),',','</col><col>') + '</col></row></rows>') AS XML)

SELECT
     t.n.value('col[1]/text()[1]','nvarchar(max)') as Col1
    ,t.n.value('col[2]/text()[1]','nvarchar(max)') as Col2
    ,t.n.value('col[3]/text()[1]','nvarchar(max)') as Col3
FROM
    @xmlstr.nodes ('/rows/row') AS t(n)

这篇关于在 XML 变量中用 NULL 替换空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)