2012-06-19 49 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