Función para obtener Dígito Verificador Mysql

CREATE FUNCTION `digitoVerificador`(rut INT UNSIGNED) RETURNS varchar(1) 
BEGIN

DECLARE dv VARCHAR(1);
DECLARE Digito INT;
DECLARE Contador INT;
DECLARE Multiplo INT;
DECLARE Acumulador INT;

SET Contador = 2;
SET Acumulador = 0;
SET Multiplo = 0;

WHILE(rut!=0) DO
SET Multiplo = (rut%10) * Contador;
SET Acumulador = Acumulador + Multiplo;
SET rut = FLOOR(rut / 10);
SET Contador = Contador + 1;
if(Contador = 8) THEN
SET Contador = 2;
END IF;
END WHILE;

SET Digito = 11 - (Acumulador%11);

SET dv = LTRIM(RTRIM(CAST(Digito as CHAR(2))));

IF(Digito = 10) THEN
SET dv = 'K';
END IF;

IF(Digito = 11) THEN
SET dv = '0';
END IF;

RETURN dv;

END

Saludos

También te podría gustar...

9 Respuestas

  1. apoyo dice:

    me funciono:

    DELIMITER $$

    DROP FUNCTION IF EXISTS `fnc_rut_dto_vrf` $$
    CREATE FUNCTION `fnc_rut_dto_vrf` (
    rut INT UNSIGNED
    ) RETURNS varchar(1)
    BEGIN

    DECLARE dv VARCHAR(1);
    DECLARE Digito INT;
    DECLARE Contador INT;
    DECLARE Multiplo INT;
    DECLARE Acumulador INT;

    SET Contador = 2;
    SET Acumulador = 0;
    SET Multiplo = 0;

    WHILE(rut!=0) DO
    SET Multiplo = (rut%10) * Contador;
    SET Acumulador = Acumulador + Multiplo;
    SET rut = FLOOR(rut / 10);
    SET Contador = Contador + 1;
    if(Contador = 8) THEN
    SET Contador = 2;
    END IF;
    END WHILE;

    SET Digito = 11 – (Acumulador%11);

    SET dv = LTRIM(RTRIM(CAST(Digito as CHAR(2))));

    IF(Digito = 10) THEN
    SET dv = ‘K’;
    END IF;

    IF(Digito = 11) THEN
    SET dv = ‘0’;
    END IF;

    RETURN dv;

    END

  2. Felipe Gonzalez dice:

    callampa tu funcion, esta mala

  3. Alejandro García Garay dice:

    Gracias por la función, pero no he logrado crearla en mi base de datos, utilizo MySQL y para acceder a ella Navicat pero no me deja crearla y no se como hacerlo, ¿alguien me puede ayudar un poco?

  4. Felipe dice:

    Funciona, solo falta agregar “DELIMITER //” al principio
    y “//” al final

  5. Claudio dice:

    Falta agregar «DELIMITER //» al principio
    y «//» al final

  6. X2 dice:

    MySQL ha dicho: Documentación

    #1064 – You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near » at line 4

  7. Hector dice:

    No sirve

Deja una respuesta

Tu dirección de correo electrónico no será publicada.