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?

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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 - I really can't tell about performance. You have to test. It might be worth trying to add a primary xml index. msdn.microsoft.com/en-us/library/bb500237.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.