There is such a table createtabletb (idint, valuevarchar (10) insertintotbvalues (1, aa) insertintotbvalues (1, bb) insertintotbvalues (2, aaa) insertintotbvalues (2, bbb) insertintotbvalues (2,
There is such a table create table tb (id int, value varchar (10) insert into tb values (1, 'A') insert into tb values (1, 'bb ') insert into tb values (2, 'aaa') insert into tb values (2, 'bbb ') insert into tb values (2 ,'
There is such a table
create table tb(id int, value varchar(10)) insert into tb values(1, 'aa') insert into tb values(1, 'bb') insert into tb values(2, 'aaa') insert into tb values(2, 'bbb') insert into tb values(2, 'ccc') insert into tb values(3, 'ddd') insert into tb values(3, 'fff')
Requirement: Convert the data into one row because the id is 3. Separated by |
1. convert data with id 3 to xml
Xml
Select '|' + (value) from tb
Where id = 3
For xml path ('')
Effect
2. Remove the first one. | replace it with a space.
The Stuff function is required. For functions like string operations, replace () right () left () substring () needs to be used.
The STUFF function inserts a string into another string. It deletes characters of the specified length from the start position in the first string, and inserts the second string into the start position of the first string.
Transact-SQL syntax conventions
Syntax
STUFF ( character_expression , start , length ,character_expression ) |
Stuff (select '|' + (value) from tb
Where id = 3
For xml path (''), 1, 1 ,'')
This statement cannot be run independently.
3. FinalImplementation
select id ,value=stuff((select '|'+(value) from tb where id=3for xml path('')),1,1,'') from tb where id=3 group by id
Ps: the result obtained by removing a where clause is different. I don't know why. Group by id has the effect of removing duplicates.
. No ------------
In the oracle database, he also has his ownImplementation. I think these things are nothing. As long as you have a need, you must have an answer, but you have no access to it. Now we are all programming on the shoulders of giants.