Ver originalDROP FUNCTION IF EXISTS SORT;DELIMITER |CREATE FUNCTION SORT(inString TEXT) RETURNS TEXTDETERMINISTICREADS SQL DATABEGIN DECLARE delim CHAR(1) DEFAULT ','; DECLARE strings INT DEFAULT 0; DECLARE forward INT DEFAULT 1; DECLARE backward INT; DECLARE remain TEXT; DECLARE swap1 TEXT; DECLARE swap2 TEXT; SET remain = inString; SET backward = LOCATE(delim, remain); WHILE backward != 0 DO SET strings = strings + 1; SET backward = LOCATE(delim, remain); SET remain = SUBSTRING(remain, backward+1); END WHILE; IF strings < 2 THEN RETURN inString; END IF; REPEAT SET backward = strings; REPEAT SET swap1 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,delim,backward-1),delim,-1); SET swap2 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,delim,backward),delim,-1); IF swap1 > swap2 THEN SET inString = TRIM(BOTH delim FROM CONCAT_WS(delim ,SUBSTRING_INDEX(inString,delim,backward-2) ,swap2,swap1 ,SUBSTRING_INDEX(inString,delim,(backward-strings)))); END IF; SET backward = backward - 1; UNTIL backward < 2 END REPEAT; SET forward = forward +1; UNTIL forward + 1 > strings END REPEAT;RETURN inString;END |DELIMITER;
Ver originalSELECT SORT(CONCAT_WS(',', 5, 1, 6)) ordenada; -- 1,5,6SELECT SORT(CONCAT_WS(',', campo1, campo2, campo3)) ordenada FROM tabla1;