【问题标题】:SQL XML select multiple attributesSQL XML 选择多个属性
【发布时间】:2012-06-19 12:57:48
【问题描述】:

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

我必须从存储在我的表的列中的 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)')

但是有语法错误:

为过程提供的参数数量不足或 函数值。

希望你能帮我找到解决办法..

问候 丹尼斯

【问题讨论】:

  • 但是您正试图将 result 分配给一个标量变量。您如何期望将 4 个值填充到一个可以包含 1 个值的变量中?

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


【解决方案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 -> 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)')

【讨论】:

  • 感谢您的快速答复。你能告诉我如何定义一个包含这个结果集的变量:select t.C.value('@accountID','int') as AccountID, t.C.value('@friendlyName','varchar(max)') as FriendlyName
  • @user1463983 - 您可以创建 table variable - 参见示例“B. 将数据插入表变量”(不幸的是,该页面上有 多个示例 B)
猜你喜欢
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2017-08-31
  • 2016-01-14
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多