/****** Object:  UserDefinedFunction [dbo].[MaesureIdentification]    Script Date: 07/29/2008 16:32:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[MaesureIdentification] (@IdentificationNumber VARCHAR(30))
RETURNS Varchar(30)
AS
BEGIN
	DECLARE 
		@ControlNumber int,
		@CharValue int,
		@CharValue1 int, 
		@ErrorPos int, 
		@ix int,
		@counter int,
		@MeasureNumber int,
		@TempNumber varchar(2),
		@Tmp varchar(30)

 		Select @MeasureNumber = 2
		Select @ControlNumber = 0

		Select @tmp = REVERSE(@IdentificationNumber)
		Set @Counter = 1
		while @counter < len(@tmp)
		Begin
			set @charvalue = Cast(substring(@tmp,@counter,1) as Int)
			if (@charvalue * @measurenumber) >= 10 
			Begin
				Set @tempnumber = cast(@charvalue * @measurenumber as Varchar)
				Set @charvalue = cast(substring(@tempnumber,1,1) as Int)
				Set @charvalue1 = cast(substring(@tempnumber,2,1) as Int)
				Set @Controlnumber = @Controlnumber + @charvalue + @charvalue1
			end
			else
			Begin
				Set @Controlnumber = @Controlnumber + (@charvalue * @measurenumber)
			end
			if @Measurenumber = 1
				Set @Measurenumber = 2
			else
				Set @Measurenumber = 1
			Set @counter = @counter + 1	
		end
		Set @Controlnumber = @Controlnumber % 10
		if @Controlnumber <> 0
			Set @Controlnumber = 10 - @Controlnumber
		Set @IdentificationNumber = @IdentificationNumber + cast(@Controlnumber as Varchar)
	
	RETURN @IdentificationNumber
END

