[英]Query an XML based on a column value in SQL
我想基於SQL中的列值查詢XML。
我的XML如下
declare @xmlValue xml =
'<Accounts>
<Account>
<ID>1</ID>
<Name>Alex</Name>
<Age>10</Age>
</Account>
<Account>
<ID>2</ID>
<Name>Richard</Name>
<Age>12</Age>
</Account>
<Account>
<ID>3</ID>
<Name>Shane</Name>
<Age>15</Age>
</Account>
</Accounts>';
現在,如果我有一個常量Id,就可以在Id上查詢XML了:
select @xmlValue.query('/Accounts[1]/Account[./ID/text()="2"]');
另外,如果我有一個變量,我可以像下面那樣使用sql:variable
variable:
declare @ID int
set @ID = 1
select @xmlValue.query('/Accounts[1]/Account[./ID/text()=sql:variable("@ID")]');
現在,我有一個表#tmpTable
和一個xml列(名為xmlValue
)。 我想查詢#tmpTable
並加入到Account
表,並從那里獲取AccountId,如下所示:
-- This does not work
select xmlValue.query('/Accounts[1]/Account[./ID/text()=a.AccountId]') as XMLResult
from #tmpTable tmp
inner join Accounts a on tmp.Id = a.Id
where a.Active = 1
我該如何實現? 任何幫助將不勝感激。
像這樣嘗試:
select xmlValue.query('/Accounts[1]/Account[./ID/text()=sql:column("a.AccountId")]') as XMLResult
from #tmpTable tmp
inner join Accounts a on tmp.Id = a.Id
where a.Active = 1
sql:column()
-與sql:variable()
類似-將列值引入XQuery
的適當方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.