Last active
December 1, 2023 23:34
-
-
Save EstebanFuentealba/6595272 to your computer and use it in GitHub Desktop.
Función MySQL para validar RUT Chile, aplicando la formula del módulo 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- ############################## | |
-- @Autor: Esteban Fuentealba | |
-- @Email: efuentealba@json.cl | |
-- ############################## | |
DROP FUNCTION IF EXISTS validate_rut; | |
delimiter // | |
CREATE FUNCTION validate_rut (RUT VARCHAR(12)) | |
RETURNS INT | |
BEGIN | |
DECLARE strlen INT; | |
DECLARE i INT; | |
DECLARE j INT; | |
DECLARE suma NUMERIC; | |
DECLARE temprut VARCHAR(12); | |
DECLARE verify_dv CHAR(2); | |
DECLARE DV CHAR(1); | |
SET RUT = REPLACE(REPLACE(RUT, '.', ''),'-',''); | |
SET DV = SUBSTR(RUT,-1,1); | |
SET RUT = SUBSTR(RUT,1,LENGTH(RUT)-1); | |
SET i = 1; | |
SET strlen = LENGTH(RUT); | |
SET j = 2; | |
SET suma = 0; | |
IF strlen = 8 OR strlen = 7 THEN | |
SET temprut = REVERSE(RUT); | |
moduloonce: LOOP | |
IF i <= LENGTH(temprut) THEN | |
SET suma = suma + (CONVERT(SUBSTRING(temprut, i, 1),UNSIGNED INTEGER) * j); | |
SET i = i + 1; | |
IF j = 7 THEN | |
SET j = 2; | |
ELSE | |
SET j = j + 1; | |
END IF; | |
ITERATE moduloonce; | |
END IF; | |
LEAVE moduloonce; | |
END LOOP moduloonce; | |
SET verify_dv = 11 - (suma % 11); | |
IF verify_dv = 11 THEN | |
SET verify_dv = 0; | |
ELSEIF verify_dv = 10 THEN | |
SET verify_dv = 'K'; | |
END IF; | |
IF DV = verify_dv THEN | |
RETURN 1; | |
ELSE | |
RETURN 0; | |
END IF; | |
END IF; | |
RETURN 0; | |
END | |
// | |
delimiter ; | |
-- SELECT validate_rut('11.111.111-1'); | |
-- SELECT validate_rut('11111111-1'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gracias amigo funciona bien.