SQL server uses custom functions and cursors

Source: Internet
Author: User

No.

Standard landCode)

Segment encoding (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 following table:

No.

Segment Encoding

Standard parcel included

1

G001

131001BG001, 131001BG002, 131001BG003

2

G002

131001BG004

3

G003

131001BG005

In the SQL server database, create a user-defined function and convert the table data into a result table through a cursor. The function code is as follows:

Copy codeThe Code is as follows:
Create function combstr (@ name nvarchar (50 ))
Returns nvarchar (300)
As
Begin
Declare @ resultStr nvarchar (300)
Declare @ tempStr nvarchar (500)
Declare @ flag int
Declare myCur cursor -- defines the cursor
For (select landCode from land where sectCode = @ name)
Open myCur -- open the cursor
Fetch next from myCur into tempStr-move the cursor down
Set @ flag = 0
While @ fetch_status = 0
Begin
If @ flag = 0
Begin
Set @ resultStr = @ tempStr
End
Else
Begin
Set @ resultStr = @ resultStr + ',' + @ tempStr
End
Set @ flag = @ flag + 1
Fetch next from myCur into @ tempStr
End
Close myCur
Deallocate myCur
Return @ 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.