SQL XML选择多个属性

时间:2012-06-19 12:57:48

标签: sql xml xml-parsing xmlnode xml-attribute

我只需要你的帮助。 我一直在寻找解决方案,但还没有任何效果。

我必须从xml文件中选择多个属性,这些属性存储在我的表的一列中。

这是文件:

<ManagerConfig>
   <AccountList>
     <Account accountID=“1“  friendlyName=“Testname1“> Test </Account>
     <Account accountID=“2“  friendlyName=“Testname2“> Test </Account>
     <Account accountID=“3“  friendlyName=“Testname3“> Test </Account>
     <Account accountID=“4“  friendlyName=“Testname4“> Test </Account>
   </AccountList
</ManagerConfig>

为此,我使用以下声明:

set @accountID = @xmlxx.value('(/ManagerConfig/AccountList/Account/@accountId)[1]', 'varchar(max)')
set @friendlyName = @xmlxx.value('(/ManagerConfig/AccountList/Account/@friendlyName)[1]', 'varchar(max)')

结果是:

accountID     friendlyname
1             Testname1

当我将值从[1]更改为[2]时获取第二个属性。这没问题。但是我需要所有这些属性并将它们导出到另一个临时表中。 我以为我可以用变量[@i]代替值:

set @accountID = @xmlxx.value('(/(ManagerConfig/AccountList/Account/@accountId)'[@i]'', 'varchar(max)')

但是存在语法错误:

  

为程序提供的参数数量不足或   功能价值。

我希望你能帮助我找到解决方案..

格尔茨 丹尼斯

1 个答案:

答案 0 :(得分:1)

假设您要转换为获取结果集(可以包含多个结果),而不是当前使用变量,例如:

select t.C.value('@accountID','int') as AccountID,t.C.value('@friendlyName','varchar(max)') as FriendlyName
from @xmlxx.nodes('/ManagerConfig/AccountList/Account') as t(C)

(原始设置和测试脚本,清除有问题的奇怪格式以及纠正Id - &gt; ID,这可能是修复的错误方向):

declare @xmlxx xml = '<ManagerConfig>
   <AccountList>
     <Account accountID="1"  friendlyName="Testname1"> Test </Account>
     <Account accountID="2"  friendlyName="Testname2"> Test </Account>
     <Account accountID="3"  friendlyName="Testname3"> Test </Account>
     <Account accountID="4"  friendlyName="Testname4"> Test </Account>
   </AccountList>
</ManagerConfig>'
declare @accountID varchar(max)
declare @friendlyName varchar(max)
set @accountID = @xmlxx.value('(/ManagerConfig/AccountList/Account/@accountID)[1]', 'varchar(max)')
set @friendlyName = @xmlxx.value('(/ManagerConfig/AccountList/Account/@friendlyName)[1]', 'varchar(max)')