SQL implements steps based on the specified delimiter decomposition string _mssql

Source: Internet
Author: User
If there is a string eg: "Sun,star,moon,clouds", in MS SQL, you want to "break this string down into elements [sun] [star] [Moon] [clouds], according to the given delimiter," and how do you implement it? To do this, create a function with the following code:
Copy Code code as follows:

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 ', ', ', ')
Results return
Sun
Star
Moon
Clouds
In the above code to do the transformation, return how many elements
Copy Code code as follows:

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 ', ', ', ')
Results return
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.