如何遍历xml元素并获取属性名称和值

时间:2014-03-11 08:57:55

标签: sql-server-2008 tsql loops xquery

我目前正在为SQL Server 2008编写一个存储过程,而且我对通过循环遍历xml感到困惑。

代码如下:

    DECLARE    @x1 XML

SELECT @x1 = '<PARAMS>
<PARAMETER NAME="Category 1">
<VALUE>Value 1</VALUE>
</PARAMETER>
<PARAMETER NAME="Category 2">
<VALUE>Value 2</VALUE>
</PARAMETER>
<PARAMETER NAME="Category 3">
<VALUE>Value 3</VALUE>
</PARAMETER>
</PARAMS>'

DECLARE 
@cnt INT, 
@totalcount INT,
@attName VARCHAR(30),
@attValue VARCHAR(30)

SELECT 
@cnt = 1,
@totalcount = @x1.value('count(/PARAMS/PARAMETER)','INT')
PRINT @totalcount;
-- loop
WHILE @cnt <= @totalcount BEGIN
SELECT
@attName =  @x1.value(
'(/PARAMS/PARAMETER/@NAME)[1]',
'VARCHAR(30)'),

@attValue = @x1.value(
'(/PARAMS/PARAMETER/VALUE)[1]',
'VARCHAR(30)')

PRINT 'Attribute Position: ' + CAST(@cnt AS VARCHAR)
PRINT 'Attribute Name: ' + @attName
PRINT 'Attribute Value: ' + @attValue
PRINT ''

SELECT @cnt = @cnt + 1
END

如何使用@cnt变量循环遍历所有xml元素?

我正在寻找的输出将是这样的:

Attribute Position: 1
Attribute Name: Category 1
Attribute Value: Value 1

Attribute Position: 2
Attribute Name: Category 2
Attribute Value: Value 2

Attribute Position: 3
Attribute Name: Category 3
Attribute Value: Value 3

1 个答案:

答案 0 :(得分:2)

这对你有用吗?不需要RBAR(逐行排列)处理和循环 - 只需将XML“分解”为关系行和列:

SELECT
    Category = XPar.value('@NAME', 'varchar(20)'),
    NodeValue = XPar.value('(VALUE)[1]', 'varchar(20)')
FROM
    @X1.nodes('/PARAMS/PARAMETER') AS XT(XPar)

输出类似于:

Category    NodeValue
------------------------
Category 1  Value 1
Category 2  Value 2
Category 3  Value 3