Function used to split strings in SQL Server

Source: Internet
Author: User
Create   Function Split (
@ Str_in Varchar ( 8000 ),
@ Separator   Varchar ( 4 ))
Returns   @ Strtable   Table (Strval Varchar ( 8000 ))
As
Begin

Declare
 @ Occurrences Int,
 @ Counter Int,
 @ Tmpstr Varchar(8000)

Set   @ Counter   =   0
If   Substring ( @ Str_in , Len ( @ Str_in ), 1 ) <>   @ Separator  
Set   @ Str_in   =   @ Str_in   +   @ Separator

Set   @ Occurrences   = ( Datalength ( Replace ( @ Str_in , @ Separator , @ Separator + ' # ' )) - Datalength ( @ Str_in )) /   Datalength ( @ Separator )
  Set   @ Tmpstr   =   @ Str_in

While   @ Counter   <=   @ Occurrences  
  Begin
Set   @ Counter   =   @ Counter   +   1
Insert   Into   @ Strtable
Values ( Substring ( @ Tmpstr , 1 , Charindex ( @ Separator , @ Tmpstr ) - 1 ))

Set   @ Tmpstr   =   Substring ( @ Tmpstr , Charindex ( @ Separator , @ Tmpstr ) + 1 , 8000 )

If   Datalength ( @ Tmpstr ) =   0
Break

  End
  Return  
End

Input string return table.
Call
Select DBO. Split ('string to be separated ', 'separator ')

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.