2011-04-05 37 views
0

我有兩個表需要根據匹配的xml進行連接。 xml的使用是因爲在設計時未知的一組值。我在下面寫了3個senarios。感謝您的任何幫助,您可以提供。如何在設計時加入兩個未知參數名稱的xml字段

表A
標識
XML

表B
標識
XML

表A
1,<parms><parm><name>Parm1</name><value>X</value></parm></parms>
2,<parms><parm><name>Parm1</name><value>Y</value></parm>
<parm><name>Parm2</name><value>123</value></parm></parms>
3, <parms><parm><name>Parm1</name><value>Y</value></parm>
<parm><name>Parm2</name><value>578</value></parm></parms>

表B
7,<parms><parm><name>Parm1</name><value>X</value></parm></parms>
8,<parms><parm><name>Parm1</name><value>Y</value></parm>
<parm><name>Parm2</name><value>123</value></parm></parms>

9,<parms><parm><name>Parm1</name><value>Y</value></parm>
<parm><name>Parm2</name><value>123</value></parm>
<parm><name>Parm2</name><value>578</value></parm></parms>

查詢像這樣的事情,但我需要的加入幫助。

 
select A.Id 
    , B.Id 
    from TableA A 
inner join TableB B 
    on ??? 

預期結果

 
A.Id B.Id 
1  7 
2  8 
3  8 
3  9 

回答

0
declare @TableA table (id int, xmlCol xml) 
declare @TableB table (id int, xmlCol xml) 

insert into @TableA values 
(1, '<parms><parm><name>Parm1</name><value>X</value></parm></parms>'), 
(2, '<parms><parm><name>Parm1</name><value>Y</value></parm> 
<parm><name>Parm2</name><value>123</value></parm></parms>'), 
(3, '<parms><parm><name>Parm1</name><value>Y</value></parm> 
<parm><name>Parm2</name><value>578</value></parm></parms>') 

insert into @TableB values 
(7, '<parms><parm><name>Parm1</name><value>X</value></parm></parms>'), 
(8, '<parms><parm><name>Parm1</name><value>Y</value></parm> 
<parm><name>Parm2</name><value>123</value></parm></parms>'), 
(9, '<parms><parm><name>Parm1</name><value>Y</value></parm> 
<parm><name>Parm2</name><value>123</value></parm> 
<parm><name>Parm2</name><value>578</value></parm></parms>') 

;with cteA as 
(
    select 
    A.id, 
    p.value('name[1]', 'varchar(50)') as Name, 
    p.value('value[1]', 'varchar(50)') as Value 
    from @TableA as A 
    cross apply A.xmlCol.nodes('parms/parm') as n(p) 
), cteB as 
(
    select 
    B.id, 
    p.value('name[1]', 'varchar(50)') as Name, 
    p.value('value[1]', 'varchar(50)') as Value 
    from @TableB as B 
    cross apply B.xmlCol.nodes('parms/parm') as n(p) 
) 
select distinct 
    A.id as 'A.id', 
    (select top 1 B.id 
    from cteB as B 
    where B.Name = B.Name and 
     B.Value = A.Value 
    order by B.id asc) as 'B.id' 
from cteA as A 
order by 1, 2 
+0

感謝的Mikael。很抱歉沒有儘早給你答案。你的回答讓我得到了我的最終解決方案。我記得敲我的頭,然後你的答案揭開了光。你搖滾! – Thomas 2012-10-16 14:55:00

相關問題