Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all XML attributes in SQL

I have an XML value list contained in a SQL Table Field that looks like so:

<valuelist xmlns="" name="VL_IncCompCondVL">
  <li value="BL" item="BLOCKED" />
  <li value="NK" item="NO KEY" />
  <li value="FL" item="FLOODED" />
  <li value="TD" item="TORN DOWN" />
  <li value="UL" item="UNABLE TO LOCATE" />
</valuelist>

I want to be able to create a temp SQL table like so:

CREATE TABLE #incompleteCode
(
value nvarchar(2),
item nvarchar(20)
)

and populate it with all the values/items from the XML so that I can use the temp table to JOIN with another SELECT statement.

SELECT Data.value('(/valuelist/li/@item)[1]', 'nvarchar(50)') AS Item
                                                    FROM ValueList
                                                    WHERE Name = 'VL_IncCompCondVL'

That statement gets me the first one, and if i increment [1] to [2] and so on, i can 1 by 1 select each attribute. But I have to believe there's a way to just get them all. I've tried some variations and am just not figuring it out. I think I need to use the * wildcard somewhere.

like image 413
nitewulf50 Avatar asked Apr 26 '13 22:04

nitewulf50


People also ask

How do I query XML data in SQL?

A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.

How do I select a specific XML node in SQL Server?

You should use the query() Method if you want to get a part of your XML. If you want the value from a specific node you should use value() Method. Update: If you want to shred your XML to multiple rows you use nodes() Method.

How do I get data from XML format in SQL Server?

SQL Server lets you retrieve data as XML by supporting the FOR XML clause, which can be included as part of your query. You can use the FOR XML clause in the main (outer) query as well as in subqueries. The clause supports numerous options that let you define the format of the XML data.

What is XML datatype in SQL?

The xml data type is a built-in data type in SQL Server and is somewhat similar to other built-in types such as int and varchar. As with other built-in types, you can use the xml data type as a column type when you create a table as a variable type, a parameter type, a function-return type, or in CAST and CONVERT.


1 Answers

You should use the nodes method:

SELECT 
  item.value('.', 'nvarchar(50)') 
FROM 
  ValueList 
  CROSS APPLY data.nodes('/valuelist/li/@item') as T2(item) 
where 
  name='VL_IncCompCondVL'

See here about CROSS APPLY

like image 119
MiMo Avatar answered Sep 18 '22 13:09

MiMo