SQL statement to break down strings based on specified delimiters

Source: Internet
Author: User

If you have a string such as "sun, star, moon, clouds", you want to use the given separator ', 'How can we break this string into [sun] [star] [moon] [clouds] elements? Create a Function with the following code:
Copy codeThe Code is 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 ',',')
Result returned
Sun
Star
Moon
Clouds
In the code above, how many elements are returned?
Copy codeThe Code is 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 ',',')
Result returned
4

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.