2

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
          )

どうすればao/pを次のように取得できますか

出力:

 UserID StateID       CityID
     1      1           10
     1      2           20
     1      2           30
     1      3            0

達成することは可能ですか?

4

1 に答える 1

5

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)
于 2011-09-13T10:45:32.023 に答える