Combine the same field of multiple records into a single string

Source: Internet
Author: User

Stuff (SELECT ', ' + fieldname from  tablename FOR XML Path (")), 1, 1, ')

The function of this whole sentence is to concatenate the contents of a multiline FieldName field, separated by commas.
such as tables
FieldName
-----------
Aaa
Bbb
Ccc
After concatenation is the string: AAA,BBB,CCC
The FOR XML path is a way to generate XML that is supported by a later version of SQL Server 2005 . Refer to Books Online for details on how to use them.
The role of the stuff function is to remove the comma delimiter from the front of the string.

---------------------------------------------------------------

在sql server 2000中只能用函数解决 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‘ go  --1. 创建处理函数  CREATE FUNCTION dbo.f_strUnite(@id  int RETURNS varchar (8000)  AS BEGIN      DECLARE @str  varchar (8000)       SET @str =  ‘‘      SELECT @str = @str +  ‘,‘ + value  FROM tb  WHERE [email protected]       RETURN STUFF(@str, 1, 1,  ‘‘ END GO  -- 调用函数  SELECt id, value = dbo.f_strUnite(id)  FROM tb  GROUP BY id    go   id          value       ----------- -----------  1          aa,bb  2          aaa,bbb,ccc   

Combine the same field of multiple records into a single string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.