SQL Server user-defined function, which loops through a certain field to form a string

Source: Internet
Author: User
Table structure. The data is as follows:
ID value
-- ---------
1 AA
1 Bb
2 Aaa
2 Bbb
2 CCC

Expected results:
IDValues
-----------------
1AA, BB
2Aaa, BBB, CCC
That is:Group ByID, calculate the sum of values (string addition)

1 . Old solution (in SQL Server 2000, only functions can be used .)
-- 1. Create a processing function
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

Create Function DBO. f_str ( @ ID Int )
Returns Varchar ( 8000 )
As
Begin
Declare @ R Varchar ( 8000 )
Set @ R = ''
Select @ R = @ R + ' , ' + Value From TB Where ID = @ ID
Return Stuff ( @ R , 1 , 1 , '' )
End
Go

--Call a function
SelectID, Value=DBO. f_str (ID)FromTBGroup ByID

Drop TableTB
Drop FunctionDBO. f_str

/*
ID value
----------------------
1 aa, BB
2 AAA, BBB, CCC
(The number of affected rows is 2)
*/

-- 2. Another function.
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

-- Create a merged Function
Create Function F_hb ( @ ID Int )
Returns Varchar ( 8000 )
As
Begin
Declare @ Str Varchar ( 8000 )
Set @ Str = ''
Select @ Str = @ Str + ' , ' + Cast (Value As Varchar ) From TB Where ID = @ ID
Set @ Str = Right ( @ Str , Len ( @ Str ) - 1 )
Return ( @ Str )
End
Go

--Call the custom function to obtain the result:
Select DistinctID, DBO. f_hb (ID)AsValueFromTB

Drop TableTB
Drop FunctionDBO. f_hb

/*
id value
----------- ---------
1 aa, BB
2 AAA, BBB, CCC
(the number of affected rows is 2)
*/

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.