Read Catalogue
- Create a test table & Insert test data
- The FOR XML path uses the
- General usage
- Custom node Name
- property of the field as XML
We usually need to get a string that is spelled out by a field of multiple rows, and we can use the FOR XML path to handle it; The specific use of the FOR XML path is described below.
Back to top Create test table & Insert test data
Add a test table to the database
CREATE TABLE MyTest ( UserName varchar), Email varchar (100))
Inserting test data
View Code
The database has the following two data
Go back to the top for XML path using
General usage
Creating XML with the root node as user
SELECT UserName, Email from MyTest for XML PATH (' User ')
Operation Result:
<User> <UserName> Zhang San </UserName> <email>[email protected]</email></user ><User> <UserName> John Doe </UserName> <email>[email protected]</email></ User>
Custom node Name
Alias the corresponding field, username alias to MyUser as follows
SELECT UserName as MyUser, Email from MyTest for XML PATH (' User ')
Run results
<User> <MyUser> Zhang San </MyUser> <email>[email protected]</email></user> <User> <MyUser> John Doe </MyUser> <email>[email protected]</email></user>
property of the field as XML
You can alias with as ' @ at query time. ' Like ' @value '
SELECT UserName as ' @UserName ', Email as ' @Email ' from MyTest for XML PATH (' User ')
Run results
<user username= "Zhang San" email= "[email protected]"/><user username= "John Doe" email= "[email protected]"/>
Row-to-column stitching string
If all names are stitched together, separated by a string
SELECT username+ ', ' from MyTest for XML PATH (')
Results
Zhang San, John Doe,
There is one more, need to be processed again, by processing the string will be the last comma is removed, can be processed by the left function in SQL, here does not introduce;
Refer to my other article for specific usage----functions commonly used to intercept strings in SQL Server
If you think reading this blog gives you something to gain, you might want to click " recommend " in the lower right corner.
If you want to find my new blog more easily, click on " Follow me "
If you want to give me more encouragement, you may wish to click on the right, " enjoy your stay"
Blog is his own summary of the results of learning, learning to summarize the knowledge-"analysis of the problem-" to solve the problem.
Where the views/descriptions in the text are incorrect, please correct them.
Thank you for your reading, if you are interested in the content of my blog, please continue to follow my following blog, I am yxtic.
SQL for XML Path usage
in SQL Server