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 中将 Float 转换为 Varchar 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01