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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With