Sql server retrieving specific data from an XML column

Friends HI I have the following table in sql server 2014 :

Table [Product]

Serie,  Int (primary key column)
Name, varchar(100)
LeftMenu, xml

Here is an example XML in the LeftMenu column that each row can have:

<menu>
<e>
<col>1</col>
<url>
/products/pressure-relief/pressure-relief-valves/general-info
</url>
<IDElement>General-Info
</IDElement>
</e>
<e>
<col>2</col>
<url>
/products/pressure-relief/pressure-relief-valves/parts
</url>
<IDElement>parts
</IDElement>
</e>
</menu>

The expected result is as follows.

Serie | col | name
-------------------
1000  |  1  | parts

From the given Serie (primary key), I want to get the node value <col>that passes the tag value <IDElement>.

This is similar to searching inside each <IDElement>in XML and returning the tag value <col>that matches this group of elements.

I try the following, but for some reason does not work:

select p.serie, p.name,
pref.value('(col())[1]', 'varchar(max)') as MenuName,
from prodInfo p 
p.[left-menu].nodes('menu/e') as names  (pref)
WHERE  
pre.value('(IDElement())[1]', 'varchar(max)') == @IDElement
AND p.serie =@serie

Could you tell me what is wrong?

, , , , , XML, - ?

!

+4
1

, , PARTS - Col 2, .

Declare @YourTable table (Series int,Name varchar(100),LeftMenu xml)
Insert Into @YourTable values
(1000,'Some Series Name','<menu><e><col>1</col><url>/products/pressure-relief/pressure-relief-valves/general-info</url><IDElement>General-Info</IDElement></e><e><col>2</col><url>/products/pressure-relief/pressure-relief-valves/parts</url><IDElement>parts</IDElement></e></menu>')

Declare @Fetch varchar(100) = 'Parts'

Select A.Series
      ,B.*
 From  @YourTable A
 Cross Apply (
                Select  Col  = B.value('col[1]','int') 
                       ,Name = B.value('IDElement[1]','varchar(100)') 
                       ,URL  = B.value('url[1]','varchar(100)') 
                From LeftMenu.nodes('/menu') AS A(Grp)
                Cross Apply A.Grp.nodes('e') AS B(B)
                --Where  B.value('IDElement[1]','varchar(100)') = @Fetch
             ) B

Series  Col Name            URL
1000    1   General-Info    /products/pressure-relief/pressure-relief-valves/general-info
1000    2   parts           /products/pressure-relief/pressure-relief-valves/parts
+2

Source: https://habr.com/ru/post/1657291/


All Articles