Database custom table-valued functions split (@LongStr, @SplitStr, @IsDistinct)

Source: Internet
Author: User

CREATE FUNCTION [dbo]. [F3_split] (@LongStr varchar (MAX), @SplitStr varchar, @IsDistinct BIT)
RETURNS @RTable TABLE (ID INT IDENTITY PRIMARY key,shortstr VARCHAR (MAX))
As BEGIN
IF ISNULL (@LongStr, ') = '--the expression is empty or null returns an empty table directly
RETURN
IF ISNULL (@SplitStr, ') = '--delimiter is empty returns a table of records (holding an expression)
BEGIN
INSERT into @RTable (shortstr) SELECT @LongStr
RETURN
END
DECLARE @Split_len INT
DECLARE @LongStr_len INT
SET @Split_len =len (@SplitStr)-The length of the delimiter
SET @LongStr_len =len (@LongStr)--The length of the current expression
While CHARINDEX (@SplitStr, @LongStr) >0
BEGIN
DECLARE @ShortStr VARCHAR (1000)--split string
SET @ShortStr =substring (@LongStr, 1,charindex (@SplitStr, @LongStr)-1-each time a delimiter is taken from the 1th position-1 is a section
SET @LongStr =substring (@LongStr, CHARINDEX (@SplitStr, @LongStr) [email Protected]_len, (@LongStr_len-len (@ShortStr) [ Email protected]_len)--the value of the transform expression is the remaining
SET @LongStr_len =len (@LongStr)--The length of the transform expression
IF @ShortStr <> ' and @IsDistinct =1
INSERT into @RTable (shortstr) SELECT @ShortStr
Where not EXISTS (SELECT 1 from @RTable WHERE[email protected])--Put the split string into the table
ELSE IF @ShortStr <> '
INSERT into @RTable (shortstr) SELECT @ShortStr
END
If @LongStr <> ' and @IsDistinct = 1--If the last section has no delimiters, go directly into the table
INSERT into @RTable (shortstr) SELECT @LongStr
Where not EXISTS (SELECT 1 from @RTable WHERE[email protected])
ELSE IF @LongStr <> '
INSERT into @RTable (shortstr) SELECT @LongStr
RETURN
END

Database custom table-valued functions split (@LongStr, @SplitStr, @IsDistinct)

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.