2012-06-19 54 views
0

我只需要你的帮助。 我正在寻找解决方案,但没有任何工程。SQL XML选择多个属性

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

对于使用下面的语句这I'm:

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 

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

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

但有一个语法错误:

An insufficient number of arguments were supplied for the procedure or function value.

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

格尔茨 丹尼斯

+0

但是你试图将* result *赋值为一个标量变量。您如何期望将4个值填入可包含1个值的变量? –

回答

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)') 
+0

谢谢你的快速回答。你能告诉我如何定义一个包含这个结果集的变量:选择tCvalue('@ accountID','int')作为AccountID,tCvalue('@ friendlyName','varchar(max)')作为FriendlyName – user1463983

+0

@ user1463983 - 您可以创建[表变量](http://msdn.microsoft.com/en-us/library/ms174335) - 请参阅示例“B.将数据插入表变量”(不幸的是,有*多*示例B的那个页面) –

+0

嗯,它的工作原理!谢谢。 – user1463983