SQL implements the split function, which allows you to customize the delimiter and retrieve the string before the delimiter.

Source: Internet
Author: User
Customizes the string before the delimiter. The default position is 0)
Format: DBO. Split (field name, 'separator ', number of strings retrieved)
If there are no separator characters, the entire string is returned.
If the position of the retrieved string exceeds the index, null is returned.

Create Function [DBO]. [split]
(@ Strnvarchar (4000), @ code varchar (10), @ No INT)
Returns varchar (200)
As
Begin

Declare @ intlen int
Declare @ count int
Declare @ indexb int
Declare @ indexe int
Set @ intlen = Len (@ code)
Set @ COUNT = 0
Set @ indexb = 1


If @ No = 0
If charindex (@ code, @ STR, @ indexb) <> 0
Return left (@ STR, charindex (@ code, @ STR, @ indexb)-1)
Else
Return @ Str

While charindex (@ code, @ STR, @ indexb) <> 0
Begin
Set @ COUNT = @ count + 1
If @ COUNT = @ No
Break
Set @ indexb = @ intlen + charindex (@ code, @ STR, @ indexb)
End


If @ COUNT = @ No
Begin

Set @ indexe = @ intlen + charindex (@ code, @ STR, @ indexb)
If charindex (@ code, @ STR, @ indexe) <> 0
Return substring (@ STR, charindex (@ code, @ STR, @ indexb) + Len (@ code), charindex (@ code, @ STR, @ indexe) -charindex (@ code, @ STR, @ indexb)-len (@ Code ))
Else
Return right (@ STR, Len (@ Str)-charindex (@ code, @ STR, @ indexb)-len (@ code) + 1)

End

Return''

End




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.