Project requirements: Multiple rows of data in a table are displayed in a single field, as follows:
For example, there are field id,name in Table A,
There are field id,pid,des in table B,
Table A, the data in table B are as follows:
ID NAME
1 sheets of three
2 John Doe
ID PID DES
11 languages
21 Mathematics
31 Foreign languages
42 History
52 geography
Finally I want to show the effect as:
ID NAME KC
1 three languages, mathematics, foreign languages
2 Li four History, geography
Method: Use the stuff function in SQL with the FOR XML path
The 1.for XML path is an XML representation of the query result set
For example, table B,select * from B FOR XML path (")
The resulting set of results is as follows:
<ID>1</ID><PID>1</PID><DES> languages </DES><ID>2 </ID><PID>1</PID><DES> math </DES><ID>3</id><pid >1</PID><DES> Foreign Languages </DES><ID>4</ID><PID>2</ Pid><des> history </DES><ID>5</ID><PID>2</PID><DES> Geography </DES>
View Code
Here the dataset is not shown as multi-row data
The 2.stuff function is used as: stuff (param1, startIndex, length, param2)
Note: Remove the length characters from the param1 in startindex (all SQL starts with 1, not 0), and then replace the deleted characters with param2.
Therefore, the format of converting multiple rows of data to one line is:
SQL displays multiple rows of data in a table in one field