SQL Server Xml命名空间查询问题

时间:2010-11-02 20:41:47

标签: xml sql-server-2008 namespaces xpath

我在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 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

另外,我偶然发现了一些关于如何在有多个名称空间时忽略所有名称空间并且你知道你没有碰撞的笔记。 Someone's blog.