Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the attribute value with XQuery in MS SQL Server 2008

I have an XML like this:

<EXP>
  <TITLES>
    <SUBTITLE CL="AXT4" FL="1" NB="Text 1"/>
  </TITLES>
  <TITLES>
    <SUBTITLE CL="BVT6" FL="2" NB="Text 2"/>
  </TITLES>
  <TITLES>
    <SUBTITLE CL="PLO7" FL="3" NB="Text 3"/>
  </TITLES>
</EXP>

Using XQuery in SQL Server 2008, How can I select Just the value of the attribute NB in a list, by rows (I need all possible values),

Example:

-- Subtitles --

Text 1

Text 2

Text 3

like image 673
Luis Avatar asked Nov 02 '09 15:11

Luis


People also ask

How do I query XML data in XQuery?

Querying in an XQuery contextIf your query invokes an XQuery expression directly, you must prefix it with the case-insensitive keyword XQUERY. To retrieve all of the XML documents previously inserted into the INFO column, you can use XQuery with either db2-fn:xmlcolumn or db2-fn:sqlquery.

How do I select a value from XML in SQL?

A.The value() method retrieves the ProductID attribute value from the XML. The value is then assigned to an int variable. Value 1 is returned as a result.

How do I find the properties of a column in SQL?

To define SQL Server table column properties: Right-click a column in the Model Explorer and click Properties. The SQL Server Table Column Editor opens. Select the table from the Table drop-down to define the columns that are available for the table.


1 Answers

DECLARE @x xml;
SET @x = N'<EXP>
  <TITLES>
    <SUBTITLE CL="AXT4" FL="1" NB="Text 1"/>
  </TITLES>
  <TITLES>
    <SUBTITLE CL="BVT6" FL="2" NB="Text 2"/>
  </TITLES>
  <TITLES>
    <SUBTITLE CL="PLO7" FL="3" NB="Text 3"/>
  </TITLES>
</EXP>
';

SELECT
    t.c.value(N'@NB', N'nvarchar(10)') AS Subtitles
FROM
    @x.nodes(N'/EXP/TITLES/SUBTITLE') t(c);

The nodes expression shreds into rows, and the value retrieves the column value.

like image 168
devstuff Avatar answered Sep 18 '22 17:09

devstuff