[嗨,我试图从SQL解析XML文件。但是路径似乎找不到数据。我不确定路径是否正确。以下是我拥有的示例xml文件:
if OBJECT_ID('temp') is not null
drop table temp
CREATE TABLE temp (data xml);
insert into temp values
(' <Services>
<Service Name="AlternativeCreditAttributes">
<Categories>
<Category Name="Default">
<Attributes>
<Attribute Name="ACA_TOF_Days_Since_LAST_PAYMENT" Value="15" />
</Attributes>
</Category>
</Categories>
</Service>
</Services>
');
GO
下面是我的data.value
代码:
SELECT data.value('(Services/Service [@Name="AlternativeCreditAttributes"]/Categories/Category[@Name="Default"]/Attributes/Attribute[@Name="ACA_TOF_Days_Since_LAST_PAYMENT"])[1]', 'varchar(100)')
FROM temp;
GO
正如您正确说的,您的XPath已完全关闭。这是@Value
属性检索的起点。
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xml_data XML);
INSERT INTO @tbl (xml_data)
VALUES ('<Services>
<Service Name="AlternativeCreditAttributes">
<Categories>
<Category Name="Default">
<Attributes>
<Attribute Name="ACA_TOF_Days_Since_LAST_PAYMENT" Value="15" />
</Attributes>
</Category>
</Categories>
</Service>
</Services>');
-- DDL and sample data population, end
SELECT col.value('(@Value)[1]', 'VARCHAR(100)') AS [Value]
FROM @tbl AS tbl
CROSS APPLY tbl.xml_data.nodes('/Services/Service[@Name="AlternativeCreditAttributes"]/Categories/Category[@Name="Default"]/Attributes/Attribute[@Name="ACA_TOF_Days_Since_LAST_PAYMENT"]') AS tab(col);
输出
+-------+
| Value |
+-------+
| 15 |
+-------+