SQL: breaks down strings Based on the given delimiter

Source: Internet
Author: User

If you have a string such as "Sun, Star, moon, clouds", you want to use the given separator ', 'How can we break this string into [Sun] [Star] [moon] [clouds] elements? Create a function with the following code:

Create Function [DBO]. [split_strbydelimiter] (@ string varchar (8000), @ delimiter char (1 ))
Returns @ temptable table (items varchar (8000 ))
As
Begin
Declare @ idx int
Declare @ slice varchar (8000)
 
Select @ idx = 1
If Len (@ string) <1 or @ string is null return
 
While @ idx! = 0
Begin
Set @ idx = charindex (@ delimiter, @ string)
If @ idx! = 0
Set @ slice = left (@ string, @ idx-1)
Else
Set @ slice = @ string
 
If (LEN (@ slice)> 0)
Insert into @ temptable (items) values (@ slice)
 
Set @ string = right (@ string, Len (@ string)-@ idx)
If Len (@ string) = 0 break
End
Return
End

Example: If you enter

Select * From DBO. split_strbydelimiter ('Sun, Star, moon, clouds ',',')

Result returned

Sun

Star

Moon

Clouds

 

In the code above, how many elements are returned?

Create Function [DBO]. [getcount_split_strbydelimiter] (@ string varchar (8000), @ delimiter char (1 ))
Returns int
As
Begin
Declare @ temptable table (items varchar (8000 ))
Declare @ splitcount int
Declare @ idx int
Declare @ slice varchar (8000)
 
Select @ idx = 1
If Len (@ string) <1 or @ string is null return 0
 
While @ idx! = 0
Begin
Set @ idx = charindex (@ delimiter, @ string)
If @ idx! = 0
Set @ slice = left (@ string, @ idx-1)
Else
Set @ slice = @ string
 
If (LEN (@ slice)> 0)
Insert into @ temptable (items) values (@ slice)
 
Set @ string = right (@ string, Len (@ string)-@ idx)
If Len (@ string) = 0 break
End
Set @ splitcount = (select count (*) from @ temptable)
Return @ splitcount
End

Example

Select DBO. getcount_split_strbydelimiter ('Sun, Star, moon, clouds ',',')

Result returned

4

 

 

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.