我在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.query
或.value
,但我能够提取单个值(例如Var1)或XML标记,<level>Var1</level>
...任何帮助都会很棒帮助
答案 0 :(得分: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>
个节点 - 我只是选择了第一个和第二个子节点 - 这可能需要根据需要进行调整关于你的数据。
答案 1 :(得分: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 强>