/****** Object:  UserDefinedFunction [dbo].[CRYPT]    Script Date: 04/29/2014 23:12:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CRYPT]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[CRYPT]
GO
GO
GO


CREATE FUNCTION [dbo].[CRYPT]( @TEXTI AS VARCHAR(50)) RETURNS VARCHAR(50) with encryption
AS
begin
 
DECLARE @CRYPTED AS VARCHAR(50)

DECLARE @SALASANA AS INT
DECLARE @TT AS INT 
DECLARE @X1 AS INT 
DECLARE @SANA AS INT 
DECLARE @G AS INT
DECLARE @CC AS INT

SET @CRYPTED ='';
SET @CC = 1;
SET @TT = LEN(@TEXTI) ;
SET @SANA = 0;
SET @SALASANA = 0;
SET @G=0;

WHILE  @TT > 0 
	BEGIN
		
		SET @SANA = ASCII(SUBSTRING (@TEXTI,@CC,1));

		SET @CC = @CC + 1;
		SET @G=@G+1;
		SET @X1=0;

		IF (@G=6)
			BEGIN
				SET @G=0
			END
 
		SET @X1 = (CASE WHEN @G=0 THEN
							@SANA - (@SALASANA -2)
						 WHEN @G=1 THEN
							@SANA + (@SALASANA -5)
						 WHEN @G=2 THEN
							@SANA - (@SALASANA -4)
						 WHEN @G=3 THEN
							@SANA + (@SALASANA -2)
						 WHEN @G=4 THEN
							@SANA - (@SALASANA -3)
						 WHEN @G=5 THEN
							@SANA + (@SALASANA -5)
					END) + @G ;
		
		SET @CRYPTED = @CRYPTED + CONVERT(VARCHAR(5),CHAR(@X1))
		SET @TT=@TT-1;

	END

	RETURN @CRYPTED;

  end

GO


