[英]sql server getting specific data from XML column
HI friends I have the following table in sql server 2014 : 嗨朋友我在sql server 2014中有以下表格:
Serie, Int (primary key column)
Name, varchar(100)
LeftMenu, xml
Here is an example of the XML in the LeftMenu column each row could have: 以下是LeftMenu列中每行可以具有的XML示例:
<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 like the following 预期结果如下
Serie | col | name
-------------------
1000 | 1 | parts
From a given Serie (the primary key), I want to get the value of the node <col>
passing the value of the <IDElement>
tag. 从给定的Serie(主键),我想得到节点<col>
的值传递<IDElement>
标记的值。
It is like searching inside each <IDElement>
in the XML and return the value of the <col>
tag that matches that group of elements. 这就像在XML中的每个<IDElement>
内部进行搜索一样,并返回与该组元素匹配的<col>
标记的值。
I am trying the following but somehow it is not working: 我正在尝试以下但不知何故它不起作用:
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 please tell me what is wrong? 你能告诉我有什么问题吗?
Other option my partner suggested is to do it as in old times and create a new table instead of using XML, any suggestions? 我的合作伙伴建议的其他选项是像过去那样做并创建一个新表而不是使用XML,任何建议?
Thank you! 谢谢!
I commented the WHERE to illustrate PARTS is Col 2, OR I completely misunderstood your requirements 我评论了WHERE来说明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
Returns 返回
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.