1
<University>
  <RegistrationCode>12859</RegistrationCode>
  <Colleges>
    <College>
      <CollegeCode>0001</CollegeCode>
      <CollegeName>NIMS</CollegeName>
    </College>
    <College>
      <CollegeCode>0002</CollegeCode>
      <CollegeName>OXFORD</CollegeName>
    </College>
  </Colleges>
</University>

I want extract below out put from above XML using SQL Query. Can someone help me on this?

RegistrationCode   CollegeCode      CollegeName
-----------------------------------------------
12859              0001             NIMS
12859              0002             OXFORD
1

1 Answer 1

1

Try this:

DECLARE @input XML = '<University>
<RegistrationCode>12859</RegistrationCode>
<Colleges>
<College>
<CollegeCode>0001</CollegeCode>
<CollegeName>NIMS</CollegeName>
</College>
<College>
<CollegeCode>0002</CollegeCode>
<CollegeName>OXFORD</CollegeName>
</College>
</Colleges>
</University>'

SELECT
    RegistrationCode = Univ.value('(RegistrationCode)[1]', 'int'),
    CollegeCode = Colleges.value('(CollegeCode)[1]', 'int'),
    CollegeName = Colleges.value('(CollegeName)[1]', 'varchar(100)')
FROM 
    @input.nodes('University') AS XTbl(Univ)
CROSS APPLY
    Univ.nodes('Colleges/College') AS XTbl2(Colleges)

That gives me your desired output.

Basically, you need to first have a list of <University> nodes (just one here) to get the registration code, and then from that <University> node you grab the <Colleges>/<College> subnodes using CROSS APPLY and you grab the college code and name from those subnodes

Sign up to request clarification or add additional context in comments.

Comments

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.