Replace empty string with NULL in XML variable(在 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 替换空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 XML 变量中用 NULL 替换空字符串
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
