[英]Transform XML to Table data using XQuery in SQL Server
是否可以在SQL Server中使用XQuery从输出中实现下表
编辑:我的要求发生了变化,请考虑我有一个表,其中存储以下xml和UserID
DECLARE @XML xml
set @XML = '<Security>
<FiscalYear Name="2012">
<Country Id="204">
<State Id="1">
<City Id="10"></City>
</State>
<State Id="2">
<City Id="20"></City>
<City Id="30"></City>
</State>
<State Id ="3"></State>
</Country >
</FiscalYear>
</Security>'
CREATE TABLE #tmp_user
(UserID INT,SecurityXML XML)
INSERT INTO #tmp_user
( UserID, SecurityXML )
VALUES ( 1,
@XML
)
现在我怎样才能像
输出:
UserID StateID CityID
1 1 10
1 2 20
1 2 30
1 3 0
有可能实现吗?
我修改了您的XML,因为它无效。 将结束标签</Subsidiary>
更改为</Country>
。
declare @XML xml
set @XML =
'<Security>
<FiscalYear Name="2012">
<Country Id="204">
<State Id="1">
<City Id="10"></City>
</State>
<State Id="2">
<City Id="20"></City>
<City Id="30"></City>
</State>
<State Id ="3"></State>
</Country>
</FiscalYear>
</Security>'
select S.N.value('@Id', 'int') as StateID,
coalesce(C.N.value('@Id', 'int'), 0) as CityID
from @XML.nodes('/Security/FiscalYear/Country/State') as S(N)
outer apply S.N.nodes('City') as C(N)
使用表格而不是XML变量的版本
select T.UserID,
S.N.value('@Id', 'int') as StateID,
coalesce(C.N.value('@Id', 'int'), 0) as CityID
from #tmp_user as T
cross apply T.SecurityXML.nodes('/Security/FiscalYear/Country/State') as S(N)
outer apply S.N.nodes('City') as C(N)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.