Función en SQL server que calcula DV
/*
La siguiente función calcula el digito verificados del texto enviado, correspondiente al Rut son guion ni digito verificador, este retorna una variable de tipo carácter.
*/
USE [PROCESO_PROV_TEST] GO /****** Object: UserDefinedFunction [dbo].[fn_calcula_dv] Script Date: 01-02-2021 12:07:06 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Jorge Hueiquiche -- Create date: 01 de Febrero del 2021 -- Description: Funcion que calcula el digito verificador -- ============================================= create FUNCTION [dbo].[fn_calcula_dv] ( -- Add the parameters for the function here @rut varchar(20) ) RETURNS int AS BEGIN
DECLARE @dv CHAR DECLARE @ntotal INT
SET @rut = REVERSE(@rut) SET @ntotal = LEN(@rut)
DECLARE @n INT = 0 DECLARE @sumarut INT = 0 DECLARE @mul INT = 1
WHILE @n < @ntotal BEGIN SET @mul = @mul + 1 SET @sumarut = @sumarut + SUBSTRING(@rut,@n+1,1) * @mul
IF @mul = 7 BEGIN SET @mul = 1 END SET @n = @n + 1 END -- fin while
DECLARE @calcdv CHAR(2) SET @calcdv = 11 - @sumarut % 11
IF @calcdv='10' BEGIN SET @calcdv='K' END ELSE IF @calcdv='11' BEGIN SET @calcdv='0' END
-- Return the result of the function RETURN @calcdv
END












