Search code examples
sqlxmlxpathxsltxquery

SQL: How can I get the value of an attribute in XML datatype?


I have the following xml in my database:

<email>
  <account language="en" ... />
</email>

I am using something like this now: but still have to find the attribute value.

 SELECT convert(xml,m.Body).query('/Email/Account')
 FROM Mail

How can I get the value of the language attribute in my select statement with SQL?


Solution

  • Use XQuery:

    declare @xml xml =
    '<email>
      <account language="en" />
    </email>'
    
    select @xml.value('(/email/account/@language)[1]', 'nvarchar(max)')
    

    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
    

    Output:

    en
    fr