在MySQL中解析复杂字符串

问题描述 投票:0回答:1

我有一个字母数字字符串列表,其中包括两个特殊字符

+
-
。如下所示,输入代表我们公司产品的部件号。我想提取各个组件作为输出。大约有 45,000 种产品,下面的数据是部件号的示例。如何解析此字符串以区分
+
-
并提供正确的输出?

我不确定如何区分

-
指示的范围和
+
指示的加法。

sql mysql string parsing concatenation
1个回答
0
投票

创建程序:

DELIMITER //
CREATE PROCEDURE ConvertToList(input_string VARCHAR(255))
BEGIN
    DECLARE output_list VARCHAR(255) DEFAULT '';
    DECLARE start_range INT;
    DECLARE end_range INT;
    DECLARE range_separator_pos INT;
    DECLARE plus_separator_pos INT;
    DECLARE current_number INT;

    -- Replace '-' with ',' to separate ranges
    SET input_string = REPLACE(input_string, '-', ',');
    
    -- Replace '+' with ',' to separate additions
    SET input_string = REPLACE(input_string, '+', ',');

    -- Process each part of the input string
    WHILE LENGTH(input_string) > 0 DO
        -- Find the position of the next range separator '-'
        SET range_separator_pos = INSTR(input_string, ',');
        IF range_separator_pos = 0 THEN
            SET range_separator_pos = LENGTH(input_string) + 1;
        END IF;

        -- Extract the current part of the input string
        SET current_number = CAST(SUBSTRING(input_string, 1, range_separator_pos - 1) AS UNSIGNED);

        -- Check if the current part represents a range or single number
        IF INSTR(input_string, '-') > 0 THEN
            -- If it's a range, extract the start and end values
            SET start_range = CAST(SUBSTRING_INDEX(input_string, '-', 1) AS UNSIGNED);
            SET end_range = CAST(SUBSTRING_INDEX(input_string, '-', -1) AS UNSIGNED);
            -- Add the range to the output list
            SET output_list = CONCAT(output_list, IF(output_list = '', '', ','), 
                                      CAST(start_range AS CHAR), '-', CAST(end_range AS CHAR));
        ELSE
            -- If it's a single number, add it to the output list
            SET output_list = CONCAT(output_list, IF(output_list = '', '', ','), CAST(current_number AS CHAR));
        END IF;

        -- Remove the processed part from the input string
        SET input_string = SUBSTRING(input_string, range_separator_pos + 1);
    END WHILE;

    SELECT output_list AS Output;
END//
DELIMITER ;

并称其为:

CALL ConvertToList('1-3+5');
© www.soinside.com 2019 - 2024. All rights reserved.