2

Is it possible to achieve the following table from of output using XQuery in SQL Server

Edit: A change in my requirement, Consider i have a table which stores the below xml and also 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
          )

Now how can i get a o/p like

Output:

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

Is it possible to achieve?

Sandeep Polavarapu
  • 382
  • 1
  • 6
  • 25

1 Answers1

5

I modified your XML a bit because it was invalid. Change the end tag </Subsidiary> to </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)

A version using a table instead of XML variable

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)
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
  • thanks a lot Mikael, +1 for ur answer, how about the performance if i am gonna run this query on a table where XML is stored (on an average 10,000 records not more than that) – Sandeep Polavarapu Sep 13 '11 at 11:16
  • @Sandeep - I really can't tell about performance. You have to test. It might be worth trying to add a primary xml index. http://msdn.microsoft.com/en-us/library/bb500237.aspx – Mikael Eriksson Sep 13 '11 at 11:23