SQL Server string cutting function _mssql

Source: Internet
Author: User
Copy code code as follows:

CREATE FUNCTION Fgetstrbysplit
(
@Source VARCHAR (max),
@Index INT,
@SplitChar VARCHAR (1)
)
RETURNS varchar (MAX)
As
BEGIN

DECLARE @Len INT
DECLARE @n INT = 0
DECLARE @ChIndex INT
DECLARE @Result VARCHAR (MAX)
--Get total length
SET @Len = Len (@Source)
--Get the cut character position
SET @ChIndex = CHARINDEX (@SplitChar, @Source)

While @ChIndex > 0
BEGIN
IF (@n = @Index)
BEGIN
SET @Source = SUBSTRING (@Source, 0, @ChIndex)
Break
End

SET @Source = SUBSTRING (@Source, @ChIndex +1, @Len)
SET @ChIndex = CHARINDEX (@SplitChar, @Source)

SET @Len = Len (@Source)
SET @n = @n + 1

End

Return @Source
End
Go

--Call
DECLARE @value VARCHAR (max)
SET @value = dbo.fgetstrbysplit (' 645002*01_45854_183677_12 ', 0, ' _ ')
PRINT @value

Results:
645002*01
--1

45854

--2

183677
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.