SQL: How can i get the value of an attribute in XM

2020-02-06 18:11发布

I have the following xml in my database:

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

I'm 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?

3条回答
We Are One
2楼-- · 2020-02-06 18:45

This should work:

DECLARE @xml XML

SET @xml = N'<email><account language="en" /></email>'

SELECT T.C.value('@language', 'nvarchar(100)')
FROM @xml.nodes('email/account') T(C)
查看更多
欢心
3楼-- · 2020-02-06 18:46

It depends a lot on how you're querying the document. You can do this, though:

CREATE TABLE #example (
   document NText
);
INSERT INTO #example (document)
SELECT N'<email><account language="en" /></email>';

WITH XmlExample AS (
  SELECT CONVERT(XML, document) doc
  FROM #example
)
SELECT
  C.value('@language', 'VarChar(2)') lang
FROM XmlExample CROSS APPLY
     XmlExample.doc.nodes('//account') X(C);

DROP TABLE #example;

EDIT after changes to your question.

查看更多
家丑人穷心不美
4楼-- · 2020-02-06 18:55

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
查看更多
登录 后发表回答