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