SQL SERVER FOR XML PATH usage

      Sometimes we need to combine multiple lines of data into one line and display them separated by commas or other methods. At this time, we can use FOR XML PATH to meet the requirements. The test data is as follows:

--Test Data
if not object_id(N'Tempdb..#T') is null
	drop table #T
Go
Create table #T([Province] nvarchar(22),[City] nvarchar(23))
Insert #T
select N'Hebei',N'Shijiazhuang' union all
select N'Hebei',N'Tangshan' union all
select N'Hebei',N'Qinhuangdao' union all
select N'Shanxi',N'Taiyuan' union all
select N'Shanxi', N'Datong'
Go
-- end of test data

      We want to display all the urban areas of the province by province, and only display one piece of data for each province, which is written as follows:

SELECT  [Province] ,
        STUFF(( SELECT  ',' + #T.[City]
                FROM    #T
                WHERE   [Province] = a.[Province]
              FOR
                XML PATH ('')
              ), 1, 1, '') AS value
FROM    #T a
GROUP BY a.[Province]

      The result is as follows:


      In this way, we have achieved our needs through FOR XML PATH. Of course, FOR XML PATH has many other uses, and there are other ways of writing the combined display method, which will be added later.


Guess you like

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