Usage of FOR XML PATH function in SQL SERVER database

Record your little bit of learning! ! ! !

1. A brief introduction to FOR XML PATH

So let ’s first introduce the FOR XML PATH. Suppose there is now a hobby table (TBJTXXCE) used to store patient information. The table structure is as follows:

 

 

 Next we look at the query result statement using FOR XML PATH as follows:

SELECT * FROM TBJTXXCE  FOR XML PATH

 

 It can be seen that FOR XML PATH can output the query results into various XML according to the rows!

      So, how to change the name of the XML line node? code show as below:   

 SELECT * FROM TBJTXXCE  FOR XML PATH('xiyouji')

 

 The above is the basic syntax operation of FOR XML PATH, which is now reflected in specific practical applications. Examples are as follows:

Now we want to know which departments "Zhu Bajie" has consulted, and what are the types of registration in these departments. The script is as follows:

SELECT B.CXM,CKSMC,LEFT(CGHZL,LEN(CGHZL)-1) as CGHZL FROM (
SELECT CXM,CKSMC,
(SELECT CGHZL+',' FROM TBJTXXCE
WHERE CKSMC=A.CKSMC
FOR XML PATH('')) AS CGHZL
FROM TBJTXXCE A
GROUP BY CXM,CKSMC
) B

Script running results:

 

The outer SELECT statement LEFT (CGHZL, LEN (CGHZL) -1) as CGHZL removes the comma after CGHZL,

The execution result of the inner statement:

SELECT CXM,CKSMC,
(SELECT CGHZL+',' FROM TBJTXXCE
WHERE CKSMC=A.CKSMC
FOR XML PATH('')) AS CGHZL
FROM TBJTXXCE A
GROUP BY CXM,CKSMC

 

Guess you like

Origin www.cnblogs.com/since-1995/p/12681571.html