Validate Chilean RUT in a SQL database

Viewed 35

I found this code at this website and is working well in SQL SERVER

    CREATE FUNCTION [dbo].[CalculaDigitoRut]
(
    @rut int
)
RETURNS char(1)
AS
BEGIN
   DECLARE @digito int
   DECLARE @contador int
   DECLARE @multiplo int
   DECLARE @acumulador int
   DECLARE @ret char

   set @contador = 2
   set @acumulador = 0
   while (@rut <> 0)
   begin
      set @multiplo = (@Rut % 10) * @contador
      set @acumulador = @acumulador + @multiplo 
      set @rut = @rut / 10 
      set @contador = @contador + 1 
      if (@contador = 8) 
         set @contador = 2 
   end
   set @digito = 11 - (@acumulador % 11) 

   if (@digito = 10)
      return ('K')
   if (@digito = 11)
      return ('0')
   return (@digito)
END

Expected result

RUT --      validation_digit
10214564            K 
3781561             6
3433444             7
3066256             3

I tried to adapt it to the MariaDB (10.3.30-MariaDB) syntax and after a few tries there weren't syntax erros but the function isn't returning the expected result.

Heres the new code for MariaDB

CREATE FUNCTION Calculate_national_id_verifier (rut INT)
    RETURNS CHAR(1)
BEGIN
   DECLARE digito INT;
   DECLARE contador INT;
   DECLARE multiplo INT;
   DECLARE acumulador INT;
   DECLARE ret CHAR;

   SET contador = 2;
   SET acumulador = 0;
  
   WHILE rut <> 0 DO
      SET multiplo = (rut % 10) * contador; 
      SET acumulador = acumulador + multiplo;
      SET rut = rut / 10;
      SET contador = contador + 1; -- 3
      IF (contador = 8) THEN
          SET contador = 2;
      END IF;
   END WHILE;
   
   SET digito = 11 - (acumulador % 11);
   

   IF (digito = 10) THEN
      RETURN ('K');
   ELSEIF (digito = 11) THEN
      RETURN ('0');
   ELSE
      RETURN (digito);
   END IF;
END;

This problem seems very dumb, I've been comparing it for hours and I can't find where is the problem and why there is a difference between both functions.

I'm using DBeaver 21.3.5 as a client to run the queries.

Here are the actual results

RUT --      validation_digit
10214564            6 
3781561             K
3433444             7
3066256             5

This is my firts time asking something so sorry if I made a mistake. I couldn't find the answer.

0 Answers
Related