SQL Server Xml 命名空间查询问题

6

我有一个XML变量@ResultData,其中包含以下内容:

<EntityKey_x005B__x005D_>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000071</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000072</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000073</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000074</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
</EntityKey_x005B__x005D_>

但是由于节点上的 xmlns=...,我似乎无法选择其中的JournalNum值。在 .Net 中,我可以执行类似于 "{http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey}KeyData" 的操作来检索它,但是在 SQL 中我会得到语法错误。

我只想将 Value 节点按文档顺序列出到一个临时表中,但这也行不通....

SELECT  IDENTITY(int,1,1) as 'ID',
    c.query('(KeyData/KeyField/Value)[1]') as 'JournalNum'
INTO    #tmpBatches
FROM    @ResultData.nodes('//EntityKey') t(c)

您有什么想法?建议?解决方案?

2个回答

15

明白了...当然,在询问之后

    ;WITH XMLNAMESPACES (N'http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey' as DYN)
    SELECT  IDENTITY(int,1,1)   
                as 'ID',
            c.value('(DYN:KeyData/DYN:KeyField/DYN:Value)[1]', 'VARCHAR(40)')
                as 'JournalNum'
    INTO    #tmpBatches
    FROM    @ResultData.nodes('//EntityKey') t(c)

非常感谢!我终于摆脱了在我的xpath查询中讨厌的命名空间。 - Alberto De Caro

0

由于您只有一个命名空间,您可以使用DEFAULT来避免到处添加前缀:

 ;WITH XMLNAMESPACES (DEFAULT N'http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey') 
        SELECT   IDENTITY(int,1,1)                                                
        as 'ID', c.value('(<strike>DYN:</strike>KeyData/DYN:KeyField/DYN:Value)[1]', 'VARCHAR(40)')
        as 'JournalNum'
            INTO #tmpBatches
        FROM @ResultData.nodes('//EntityKey') t(c)

另外,我偶然发现了一些关于如何忽略所有命名空间的笔记,适用于有多个命名空间且您知道不会有冲突的情况。 某人的博客。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接