SQL server multi-row data splicing instance method

Source: Internet
Author: User

1. Table Structure
Id type productCode
1 pencil 0001
2 pencil 0002
3 pencil 0003
4 pen 0004
5 pen 0005
6 pen 0004
7 ballpoint pen 0007
8 ballpoint pen 0008
9 ballpoint pen 0007
2. Custom function fun
Copy codeThe Code is as follows:
GO
/***** Object: UserDefinedFunction [dbo]. [fun] Script Date: 11/22/2011 16:09:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create function [dbo]. [fun] (@ type nvarchar (10 ))
Returns nvarchar (200)
As
Begin
Declare @ re nvarchar (200)
Declare @ code nvarchar (200)
Set @ re =''
Set @ code =''
Select @ re = @ re + productCode + ', 'From T where type = @ type group by productCode
Select @ re = left (@ re, len (@ re)-1)
Return @ re
End

3. query statement
Select type, dbo. fun (type) from (select distinct type from T)
Result:
Pen 0004,0005
Pencil 0001,0002, 0003
Ballpoint pen 0007,0008

Related Article

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.