MySQL - creating a user-defined function for a custom sort

前端 未结 1 797
天涯浪人
天涯浪人 2020-12-10 16:22

I\'m working with a large set of legacy data (converted from a flat-file db), where a field is formatted as the last 2 digits of the year the record was entered, followed by

相关标签:
1条回答
  • 2020-12-10 16:52

    You have some problems with your substrings, and the cast to int at the end makes it sort values with more digits at the end, not by year. This should work better;

    DELIMITER //
    
    CREATE FUNCTION custom_sort(id VARCHAR(8))
        RETURNS VARCHAR(10)
        READS SQL DATA
        DETERMINISTIC
        BEGIN
            DECLARE year VARCHAR(2);
            DECLARE balance VARCHAR(6);
            DECLARE stringValue VARCHAR(10);
            SET year = SUBSTRING(id, 1, 2);
            SET balance = SUBSTRING(id, 3, 6);
            IF(year <= 96) THEN
                SET stringValue = CONCAT('20', year, balance);
            ELSE
                SET stringValue = CONCAT('19', year, balance);
            END IF;
            RETURN stringValue;
        END//
    
    DELIMITER ;
    

    This can be simplified a bit to;

    DELIMITER //
    
    CREATE FUNCTION custom_sort(id VARCHAR(8))
        RETURNS varchar(10)
        DETERMINISTIC
        BEGIN
            IF(SUBSTRING(id, 1, 2) <= '96') THEN
                RETURN CONCAT('20', id);
            ELSE
                RETURN CONCAT('19', id);
            END IF;
        END//
    
    DELIMITER ;
    
    0 讨论(0)
提交回复
热议问题