我有两个结构与此类似的表:
Table1 ([Table1Id] INT,
[Sequence] INT,
[Table2Id] INT)
Table2 ([Table2Id] INT,
[XMLData] XML)
表2中XML的基本部分是:
<Root>
<Record>
<Sequence>1</Sequence>
<Order>
<Product>Widget</Product>
</Order>
</Record>
<Record>
<Sequence>2</Sequence>
<Order>
<Product>Bolt</Product>
</Order>
</Record>
</Root>
我需要能够从表1加入表2,然后根据序列号提取相应的Record,以便得到如下结果集:
Table1Id Table2Id Sequence Product
-------- -------- -------- -----------
1 1 1 Widget
1 1 2 Bolt
我不确定如何获得这个结果。任何帮助将不胜感激。
答案 0 :(得分:2)
在xquery中的谓词中使用sql:column()
,您可以将XML中的Sequence值与Table1中的Sequence值进行比较。
select T1.Table1ID,
T1.Table2Id,
T1.Sequence,
T2.XMLData.value('(/Root/Record[Sequence/text() = sql:column("T1.Sequence")]/Order/Product/text())[1]', 'nvarchar(50)') as Product
from Table1 as T1
inner join Table2 as T2
on T1.Table2Id = T2.Table2Id