SQL SERVER Manipulate XML

       Sometimes our data is stored in the form of XML, so when reading and displaying, we need to process the format, display the data in the form we want, and test the data:

declare @x xml
 
select @x='
<root>
<info><person><name>Tom</name><old>18</old></person><marks><English>78</English><history>81</history></marks></info>
<info><person><name>John</name><old>21</old></person><marks><English>66</English><history>71</history></marks></info>
<info><person><name>Mary</name><old>19</old></person><marks><English>72</English><history>77</history></marks></info>
</root>'

       This is some data about students and grade information, including name, age, history and English grades. We want to display these field data. The processing statement is as follows:

select name=o2.value('name[1]','varchar(10)'),
       old=o2.value('old[1]','varchar(10)'),
       English=o3.value('English[1]','varchar(10)'),
       history=o3.value('history[1]','varchar(10)')
 from (select x=@x) a
 cross apply x.nodes('/root/info') x(o)
 cross apply o.nodes('person') y(o2)
 cross apply o.nodes('marks') z(o3)

       result:


       Above we processed the data in XML format through SQL and got the result as we wanted.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325808462&siteId=291194637