SQL Server uses custom functions and cursor _mssql

Source: Internet
Author: User

Number

Standard parcel Code (LANDCODE)

Section Code (SECTCODE)

1

131001bg001

G001

2

131001bg002

G001

3

131001bg003

G001

4

131001bg004

G002

5

131001bg005

G003

Now you need to convert the data in the table to the results shown in the following table:

Number

Section coding

Included Standard parcel

1

G001

131001bg001,131001bg002,131001bg003

2

G002

131001bg004

3

G003

131001bg005

In the SQL Server database, create a custom function that converts the table's data into a result table through a cursor, as shown in the function code:

Copy Code code as follows:
Create function Combstr (@name nvarchar ()
returns nvarchar ()
As
begin
Declare @resultStr nvarchar
declare @tempStr nvarchar ()
declare @flag int
D Eclare mycur Cursor--defines a cursor
for (select Landcode from Land where sectcode= @name)
Open mycur–-opening cursor
Fetch Next from Mycur into tempstr– moves the cursor down the
set @flag =0
while @ @fetch_status =0
Begin
If @flag =0
Begi N
Set @resultStr = @tempStr
End
Else
Begin
Set @resultStr = @resultStr + ', ' + @tempStr
End
Set @flag = @flag +1
Fetch NEXT from mycur to @tempStr
End
Close mycur
deallocate mycur
R Eturn @result
End
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.