Validar RUT (Chile) por Transaction

Post express de un código para validar que el RUT ingresado en el socios de negocios es un RUT válido.
Este código me lo pasaron hace años…ya ni recuerdo donde.


IF @object_type = '2' AND @transaction_type IN ('A','U')
BEGIN
     DECLARE @Rut_SN VARCHAR(12)
     SET @Rut_SN = (SELECT LicTradNum FROM OCRD WHERE CardCode = @list_of_cols_val_tab_del)
                    
     DECLARE @Rut_Par Char(12)
     DECLARE @msgType SmallInt
          ,@retorno  SmallInt
          ,@msg Char(12)
          ,@msgTitle Char(12)
          ,@RutDV Char(12)
          ,@Rut VarChar(12)
          ,@DV Char(1)
          ,@vRut Char(12)
          ,@ValidaRut SmallInt
          ,@i SmallInt
          ,@suma SmallInt
          ,@j SmallInt
          ,@Modulo SmallInt
          ,@Resta SmallInt
          ,@Valid Char(1)

          Set @Rut_Par = (SELECT LicTradNum FROM OCRD WHERE CardCode = @list_of_cols_val_tab_del)
          Set @RutDV = LTrim(RTrim(@Rut_Par))
          Set @DV = Right(@RutDV,1)
          Set @Rut = Left(@RutDV,len(@RutDV)-2)
          Set @Rut = Replace(@Rut,'.', '')
    
          If @Rut <> ' '
               Begin
                           Set @vRut = @Rut
               End
               Else
               Begin
                           Set @vRut = '0'
                           Set @DV = ' '
               End      
          Set @i = Len(@vRut)
          Set @suma = 0
          Set @j = 2
          While @i <> 0
          Begin
               If @j > 7 
               Begin 
                    Set @j = 2 
               End
               Set @suma = @suma + ((SubString(@vRut, @i, 1)) * @j)        
               Set @j = @j + 1        
               Set @i = @i - 1
          End
          Set @Modulo = @suma - Round(@suma / 11, 0) * 11
          Set @Resta = 11 - @Modulo
          If @Resta = 10 
               Set @Valid = 'K'
          Else
          If @Resta = 11 
               Set @Valid = '0'
          Else 
               Set @Valid = LTrim(RTrim(Str(@Resta)))
          Set @Rut = RTrim(Left(@RutDV,len(@RutDV)-2)) + '-' + Rtrim(LTrim(@Valid))
               
     IF @RUT != @Rut_SN
     BEGIN
          SELECT @error = -1000,@error_message = 'Rut incorrecto'
     END
END

Saludos

También te podría gustar...

Deja una respuesta

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