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 替换空字符串
基础教程推荐
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
