Home > Database > Mysql Tutorial > How Can I Retrieve Attribute Values from XML Data in SQL?

How Can I Retrieve Attribute Values from XML Data in SQL?

Linda Hamilton
Release: 2024-12-25 21:03:11
Original
987 people have browsed it

How Can I Retrieve Attribute Values from XML Data in SQL?

Retrieving Attribute Values from XML Datatype in SQL

When working with XML data in SQL, it's often necessary to extract the values of specific attributes. For instance, we may need to obtain the value of the "language" attribute from the following XML:

<email>
  <account language="en" ... />
</email>
Copy after login

To achieve this, we can leverage XQuery expressions. Here's a modified version of your SQL query using XQuery:

SELECT @xml.value('(/email/account/@language)[1]', 'nvarchar(max)') FROM Mail
Copy after login

In this query, we use the .value() function to query the XML document represented by the "@xml" variable. The XQuery expression "/email/account/@language" specifies the path to the desired attribute, and the "[1]" ensures that we retrieve the value of the first (and only) matching attribute.

Alternatively, you can use the following table expression to retrieve the attribute values:

declare @t table (m xml)

insert @t values 
    ('<email><account language="en" /></email>'), 
    ('<email><account language="fr" /></email>')

select m.value('(/email/account/@language)[1]', 'nvarchar(max)')
from @t
Copy after login

This approach provides a more concise and scalable solution for retrieving attribute values from multiple XML documents in a table. The output of the query will be:

en
fr
Copy after login

The above is the detailed content of How Can I Retrieve Attribute Values from XML Data in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template