Get the App
SLTechnology News&Howtos  ›  Database  › 

How to decompose a string according to a specified delimiter in SQL

Shulou Source: shulou.com Published: 2022-05-31 19:26:02 09月20日 Update

SQL how to decompose strings according to the specified delimiter, for this problem, this article details the corresponding analysis and solution, hoping to help more small partners who want to solve this problem find a simpler and easier way.

If you have a string eg: "sun,star,moon,clouds" and you want to break this string into elements [sun] [star] [moon] [clouds] in MS SQL according to the given delimiter ',' how do you do that? To do this, create a Function with the following code: Copy the code with the following code: 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)0) INSERT INTO @temptable(Items) VALUES(@slice) SET @String = RIGHT(@String,len(@String) - @idx) IF len(@String) = 0 break END RETURN END

Examples: If SELECT * FROM dbo.Split_StrByDelimiter ('sun,star,moon,clouds',',') returns sun star moon clouds in the above code deformation, returns how many elements copied 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)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_StrByMinimiter ('sun,star,moon, clouds',',') Returns 4

About SQL how to break down the string according to the specified delimiter questions to share here, I hope the above content can be of some help to everyone, if you still have a lot of doubts not solved, you can pay attention to the industry information channel to learn more related knowledge.

Tags: Code characters strings delimiters questions elements more examples results help answers easy to do for this easy content guys partners methods knowledge articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Technology MariaDB Shulou Tech Info vpn