1

我在 SQL Server 2005 中有一个 XML 列:

<treatmentDetails>
      <treatmentFactor>
        <treatmentFactorName>Varieties</treatmentFactorName>
        <plot>Whole</plot>
        <levels>
          <level>Var1</level>
          <level>Var2</level>
        </levels>
      </treatmentFactor>
      <treatmentFactor>
        <treatmentFactorName>Nitrogen</treatmentFactorName>
        <plot>Whole</plot>
        <levels>
          <level>N1</level>
          <level>N2</level>
          <level>N3</level> 
        </levels>
      </treatmentFactor>
</treatmentDetails>

由此,我想创建这样的输出:

Varieties Nitrogen    
Var1      N1         
var1      N2
var1      N3
var2      N1
var2      N2
var3      N3

我尝试使用xmlfield.queryor .value,但我能够提取单个值(例如 Var1)或 XML 标记,<level>Var1</level>......任何帮助都会有很大帮助。

4

2 回答 2

0

尝试这个:

DECLARE @Test TABLE (ID INT NOT NULL, XmlContent XML)

INSERT INTO @TEST VALUES(1, '<treatmentDetails>
      <treatmentFactor>
        <treatmentFactorName>Varieties</treatmentFactorName>
        <plot>Whole</plot>
        <levels>
          <level>Var1</level>
          <level>Var2</level>
        </levels>
      </treatmentFactor>
      <treatmentFactor>
        <treatmentFactorName>Nitrogen</treatmentFactorName>
        <plot>Whole</plot>
        <levels>
          <level>N1</level>
          <level>N2</level>
          <level>N3</level> 
        </levels>
      </treatmentFactor>
</treatmentDetails>')

SELECT
    Varieties = TDLevel.value('(.)[1]', 'varchar(20)'),
    Nitrogen = TDLevel2.value('(.)[1]', 'varchar(20)')
FROM
    @test
CROSS APPLY
    XmlContent.nodes('/treatmentDetails/treatmentFactor[1]/levels/level') AS Tbl(TDLevel)
CROSS APPLY
    XmlContent.nodes('/treatmentDetails/treatmentFactor[2]/levels/level') AS Tbl2(TDLevel2)

这会给我一个类似于您正在寻找的输出。

但是:我不清楚您是否总是只有两个<treatmentFactor>节点<treatmentDetails>- 我只是选择第一个和第二个子节点 - 这可能需要根据您的数据进行一些调整。

于 2012-11-26T07:33:00.220 回答
0

尝试这个

select
    TV.V.value('(.)[1]', 'varchar(20)'),
    TN.N.value('(.)[1]', 'varchar(20)')
from table1 as A
    outer apply Data.nodes('/treatmentDetails/treatmentFactor[treatmentFactorName = "Varieties"]/levels/level') as TV(V)
    outer apply Data.nodes('/treatmentDetails/treatmentFactor[treatmentFactorName = "Nitrogen"]/levels/level') as TN(N)

sql fiddle demo

于 2012-11-26T07:39:53.683 回答