All rows of a certain field in the database are concatenated

Source: Internet
Author: User

Recently, I encountered a problem where I had to query some information from the Internet by spelling a field in the data table. I found that only the scalar function was written.

.

-- 1 create a table
Create Table product (productid varchar (20), productname varchar (20 ))
Go

-- 2 Data
Insert into product values ('w001', 'hongda ')
Insert into product values ('w002', 'apsara ')
Insert into product values ('w003 ', 'Hero ')

Insert into product values ('w004 ', 'Hero ')
Insert into product values ('w005, 'Hero ')
Insert into product values ('w006 ', 'human ')
Go

-- 3 create a user-defined function
Create Function getstr (@ pname varchar (20 ))
Returns varchar (8000)
As
Begin
Declare @ retstr varchar (8000)
Set @ retstr =''
Select @ retstr = @ retstr + ',' + productid from product where productname = @ pname
Set @ retstr = stuff (@ ret, 1, 1 ,'')
Return @ retstr
End
Go

-- 4 run
Select productid = DBO. getstr (productname), productname
From Product
Group by productname order by productname

The execution result, um, finally reaches the desired output.

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.