Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - Transformation of result set of sql select statement
Transformation of result set of sql select statement
SQL statement merge string:

Select' string 1'+' string 2'+' string 3'+' string 4'+ column 1+ column 2+ column 3 ... from the table.

Remember, you should use the function: cast to convert all columns to string format. For example, if column 2 is an int data type, it can be written as

Select' string1'+'string2'+'string3'+'string4'+column1+cast (column 2 is varchar( 100))+ column 3 ... from the table.

The following is to combine multiple rows of results into one string.

-Generate test tables and insert test data.

Create table tb(id int, value varchar( 10)).

Insert tb value (1,' aa')

Insert tb value (1,' bb')

Insert into tb value (2, "aaa")

Insert into tb value (2, "bbb")

Insert into tb value (2, "ccc")

go to

-The first monitor

Select id, [val]= (

Select [value]+','from tb as b where b.id = a.id for XML path (')) from TB as a.

-The first display result

- 1 aa,bb,

- 1 aa,bb,

-2 aaa, bbb, ccc,

-2 aaa, bbb, ccc,

-2 aaa, bbb, ccc,

-The second monitor

Select id, [val]= (

Select [value]+','from tb as b where b.id = a.id for XML path (')) from TB as a.

Group by id

-Display the results for the second time.

- 1 aa,bb,

-2 aaa, bbb, ccc,

-The third monitor

select id,[val]=stuff(

Select',' +[value] from tb as b where b.id = a.id for xml path (')), 1, 1,'') from tbas a.

Group by id

-Display the results for the third time

- 1 aa,bb

-2 aaa, bbb, ccc