SQL string split function

Source: Internet
Author: User

SQL string split function

Splits a string by a specified character.

Idea: 1. Calculate the index of the specified delimiter in the string,


2. Split the string.

The SQL code is as follows:

Declare @ strorder nvarchar (200)
Declare @ ismulorder int
Declare @ firstOrder nvarchar (200)
Declare @ secondOrder nvarchar (200)

Set @ strorder = 'lastmodifydate Desc, OurPrice Asc'

Select CHARINDEX (',', @ strorder, 0)
-- Select LEN (@ strorder)
-- Select SUBSTRING (@ strorder, 0, CHARINDEX (',', @ strorder, 0 ))
-- Select SUBSTRING (@ strorder, CHARINDEX (',', @ strorder, 0) + 1, LEN (@ strorder ))
Set @ ismulorder = CHARINDEX (',', @ strorder, 0)
If @ ismulorder> 0
Begin
Set @ firstOrder = 'p. '+ SUBSTRING (@ strorder, 0, CHARINDEX (', ', @ strorder, 0 ))
Set @ secondOrder = 'p. '+ SUBSTRING (@ strorder, CHARINDEX (', ', @ strorder, 0) + 1, LEN (@ strorder ))
Set @ strorder = @ firstOrder + ',' + @ secondOrder
End


Select @ strorder

Use the split function

Create function [dbo]. [split]
(
@ SourceSql varchar (8000 ),
@ StrSeprate varchar (10)
)
Returns @ temp table (F1. varchar (100 ))
As
Begin
Declare @ I int
Set @ SourceSql = rtrim (ltrim (@ SourceSql ))
Set @ I = charindex (@ StrSeprate, @ SourceSql)
While @ I> = 1
Begin
If len (left (@sourcesql, @ i-1)> 0
Begin
Insert @ temp values (left (@ SourceSql, @ i-1 ))
End
Set @ SourceSql = substring (@ SourceSql, @ I + 1, len (@ SourceSql)-@ I)
Set @ I = charindex (@ StrSeprate, @ SourceSql)
End
If @ SourceSql <>''
Insert @ temp values (@ SourceSql)
Return
End
 
Select * from split (', 777, 11, 888, 88, 1122,888, 88,77, 00, 00 ',',')

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.