[英]Returning data from XML data in a column in a SQL Server database
Trying to extract data from a column in a SQL Server table.尝试从 SQL 服务器表中的列中提取数据。 The column however is not of type XML
but the data is in XML format (see below).然而,该列不是XML
类型,但数据采用 XML 格式(见下文)。 I can extract the data I need via the CAST
function, but looking to see if there's a more efficient query to do so.我可以通过CAST
function 提取我需要的数据,但我想看看是否有更有效的查询来这样做。
The data below exists in the details
column of table FoodTable
.以下数据存在于表FoodTable
的details
列中。 I would like to query the table to get a list of all 'prod' (ie apple, blueberry, cherry) from <FoodCity>
.我想查询表格以获取<FoodCity>
中所有“产品”(即苹果、蓝莓、樱桃)的列表。 The data is much larger in reality so would like help with more efficient query if possible.数据实际上要大得多,所以如果可能的话,希望能帮助您进行更高效的查询。
I have the following:我有以下内容:
SELECT
CAST(details AS xml).value('(//GROCER/prod[@key="apple"]/@key)[1]', 'nvarchar(max)') AS 'apple',
CAST(details AS xml).value('(//GROCER/prod[@key="blueberry"]/@key)[1]', 'nvarchar(max)') AS 'blueberry',
CAST(details AS xml).value('(//GROCER/prod[@key="cherry"]/@key)[1]', 'nvarchar(max)') AS 'cherry'
FROM
ABC.FoodTable
XML looks like this: XML 看起来像这样:
<GROCER>
<FoodCity>
<prod key = 'apple' value = '1.00'>
<prod key = 'blueberry' value = '2.00'>
<prod key = 'cherry' value = '5.00'>
</FoodCity>
<DiscountGrocer>
<prod key = 'pear' value = '3.00'>
<prod key = 'peach' value = '4.00'>
<prod key = 'kiwi' value = '6.00'>
</DiscountGrocer>
</GROCER>
Although my query above works, just looking to make it more efficient and simpler if possible.虽然我上面的查询有效,但如果可能的话,只是希望让它更高效、更简单。
| | apple |苹果 | | | blueberry |蓝莓 | | | cherry |樱桃 |
Thank you.谢谢你。
While waiting for your DDL and sample data population.在等待您的 DDL 和示例数据填充时。 Here is a conceptual example.这是一个概念性的例子。
It is using XQuery methods .nodes()
and .value()
to shred XML and convert it into a rectangular/relational format.它使用 XQuery 方法.nodes()
和.value()
分解 XML 并将其转换为矩形/关系格式。
SQL SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, details NVARCHAR(max));
INSERT INTO @tbl (details) VALUES
(N'<GROCER>
<FoodCity>
<prod key="apple" value="1.00"/>
<prod key="blueberry" value="2.00"/>
<prod key="cherry" value="5.00"/>
</FoodCity>
<DiscountGrocer>
<prod key="pear" value="3.00"/>
<prod key="peach" value="4.00"/>
<prod key="kiwi" value="6.00"/>
</DiscountGrocer>
</GROCER>');
-- DDL and sample data population, end
;WITH rs AS
(
SELECT id, CAST(details AS XML) AS xmldata
FROM @tbl
)
SELECT c.value('@key', 'VARCHAR(20)') AS product
, c.value('@value', 'DECIMAL(5,2)') AS price
FROM rs CROSS APPLY xmldata.nodes('/GROCER/*/prod') AS t(c);
Output Output
+-----------+-------+
| product | price |
+-----------+-------+
| apple | 1.00 |
| blueberry | 2.00 |
| cherry | 5.00 |
| pear | 3.00 |
| peach | 4.00 |
| kiwi | 6.00 |
+-----------+-------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.