【问题标题】:SQL Server 2014: apply against xml nodes() function suddenly stops workingSQL Server 2014:针对 xml 节点()函数应用突然停止工作
【发布时间】:2020-11-18 18:18:10
【问题描述】:

我有一个存储过程突然开始在两台假定等效的 SQL Server 2014 机器(主和故障转移)中的一台上返回 NULL。

突然出现异常的具体操作是:

    declare @skus TABLE (intSkuId int, attributes xml);
    insert into @skus
    VALUES
        (11443, '<attributes><style>basic_mug</style><color>white</color><size>15oz</size></attributes>'),
        (11444, '<attributes><style>basic_mug</style><color>black</color><size>15oz</size></attributes>');

    select 
        s.intSkuId, s.xmlAttributes,  
        att.query('.') as element 
    from 
        tb_Skus s
    outer apply 
        xmlAttributes.nodes(N'//attributes/*') as atts(att)
    where 
        s.intSkuId = 11443;

请注意,这通常会针对tb_Skus 表的一部分运行,而不是单个值,但我出于调试目的进行了简化。

这将返回以下结果:

intSkuId: 11443
xmlAttributes: <attributes><style>basic_mug</style><color>white</color><size>15oz</size></attributes>
element: NULL

另请注意,以下脚本按预期工作:

DECLARE @x xml;

SELECT @x = xmlAttributes 
FROM tb_Skus s 
WHERE s.intSkuId = 11443

SELECT @x AS xmlAttributes, att.query('.') AS element
FROM @x.nodes(N'//attributes/*') AS atts(att)

为 xmlAttribute 产生相同的值,但我得到了元素的预期值:

<style>basic_mug</style>
<color>white</color>
<size>15oz</size>

那么,第一个查询有问题吗?如果没有,是否有会话或数据库设置可以改变此函数的行为?

【问题讨论】:

  • 在提出问题时,您需要提供一个可重现的最小示例:(1) DDL 和样本数据填充,即 CREATE 表加上 INSERT、T-SQL 语句。 (2) 你需要做什么,即逻辑,以及你在 T-SQL 中尝试实现它。 (3) 基于上述#1 中的样本数据的期望输出。 (4) 你的 SQL Server 版本 (SELECT @@version;)
  • ...二进制值应该相同:select attributes.value('local-name(/*[1])', 'nvarchar(max)'), cast(attributes.value('local-name(/*[1])', 'nvarchar(max)') as varbinary(100)) as xmlbinary, cast(N'attributes' as varbinary(100)) strbinary from tb_Skus where intSkuId = 11443

标签: sql-server xml


【解决方案1】:

在这种情况下不需要使用.nodes() 方法。只有在需要将 XML 数据类型转换/分解为矩形/关系数据时才需要它。

请尝试以下方法。

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (intSkuId INT, xmlAttributes XML);
INSERT INTO @tbl (intSkuId, xmlAttributes) VALUES
(11443,  N'<attributes>
    <style>basic_mug</style>
    <color>white</color>
    <size>15oz</size>
</attributes>');
-- DDL and sample data population, end

SELECT *
    , xmlAttributes.query('/attributes/*') AS [element]
FROM @tbl
where intSkuId=11443;

【讨论】:

  • 我已经尽可能地简化了查询,但是我在这里使用.nodes()的原因是因为我需要在local-name(.)和att.value(N'(.text())[1]', 'nvarchar(50)')的函数上加入另一个表.上面的查询给了我一个包含所有子元素和值的行;我需要每一个都在自己的行中,以便我可以单独比较这些值(我的预期值在我上面的最终code 块中)
  • @JonAgnich,感谢您的澄清。尽管您身边的(1)仍然缺失。我们需要一个完整的复制。
  • @JonAgnich,请在 LinkedIn 上与我联系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多