SqlServer XQuery总是连接两个字段

时间:2014-02-07 09:12:11

标签: sql-server-2012 xquery-sql

我想从xml字段中的一列中获取一些数据:

<CDirData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://Fnet.ESB.Schemas.CentroDirectivo.CDirData">
  <ProcedureData xmlns="">
    <ProcedureId>7001</ProcedureId>
    <CentroDirectivo>Subsecretaria</CentroDirectivo>
  </ProcedureData>
  <SolicitudData xmlns="">
...

我的查询

    SELECT  top 1
        [Message].query('//*[local-name()="ProcedureId"]').value('.','nvarchar(max)') as R
    from 
        ManagementCenterQueueHistorical

但总是返回字段concat

enter image description here

我只需要第一个

提前致谢!

1 个答案:

答案 0 :(得分:1)

将XPath表达式放在括号中并添加[1]以仅从组中获取第一个元素

DECLARE @x XML = '<CDirData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://Fnet.ESB.Schemas.CentroDirectivo.CDirData">
  <ProcedureData xmlns="">
    <ProcedureId>7001</ProcedureId>
    <CentroDirectivo>Subsecretaria1</CentroDirectivo>
  </ProcedureData>
  <ProcedureData xmlns="">
    <ProcedureId>7002</ProcedureId>
    <CentroDirectivo>Subsecretaria2</CentroDirectivo>
  </ProcedureData>
  <ProcedureData xmlns="">
    <ProcedureId>7003</ProcedureId>
    <CentroDirectivo>Subsecretaria3</CentroDirectivo>
  </ProcedureData>
  <ProcedureData xmlns="">
    <ProcedureId>7004</ProcedureId>
    <CentroDirectivo>Subsecretaria4</CentroDirectivo>
  </ProcedureData>
  </CDirData>'

SELECT
    @x.query('(//*[local-name()="ProcedureId"])[1]').value('.','nvarchar(max)') as R
相关问题