2017-08-31 99 views
0

以下SQL Server(2008版)的代碼如何選擇名稱等於變量值的屬性?

declare @x xml = ' 
<PKs> 
    <Column Name="a" /> 
    <Column Name="b" /> 
</PKs> 
<Selected> 
    <row a="444010" b="2" /> 
    <row a="444012" b="3" /> 
    <row a="444003" b="2" /> 
    <row a="444009" b="4" /> 
    <row a="444002" b="3" /> 
    <row a="444005" b="1" /> 
</Selected>' 

declare @s nvarchar(max) = @x.query(' 
for $r in /Selected/row 
return <s>({ 
    for $k in /PKs/Column 
    return <s>{data($k/@Name)} = {data($r[.=$k/@Name])} and </s>}1=1) or 
    </s>').value('.', 'nvarchar(max)') 
print @s 

回報

 
(a = and b = and 1=1) or 
    (a = and b = and 1=1) or 
    (a = and b = and 1=1) or 
    (a = and b = and 1=1) or 
    (a = and b = and 1=1) or 
    (a = and b = and 1=1) or 

預期的結果是

 
(a = 444010 and b = 2 and 1=1) or 
    (a = 444012 and b = 3 and 1=1) or 
    (a = 444003 and b = 2 and 1=1) or 
    (a = 444009 and b = 4 and 1=1) or 
    (a = 444002 and b = 3 and 1=1) or 
    (a = 444005 and b = 1 and 1=1) or 

的問題是在該行return <s>{data($k/@Name)} = {data($r[.=$k/@Name])} and </s>}1=1) or,我需要選擇值爲$r/@($k/@Name)(其中有語法錯誤),而不是$r[.=$k/@Name]

回答

2

動態計算的屬性名稱是不是真的慣用的XQuery,但它可以通過枚舉使用@*,然後所有屬性手動過濾使用fn:local-name()你想通過訪問它的名字之一進行:

for $r in /Selected/row 
return <s>({ 
    for $k in /PKs/Column 
    let $col := $r/@*[local-name()=$k/@Name] 
    return <s>{data($k/@Name)} = {data($col)} and </s>}1=1) or 
    </s> 
相關問題