USE [HRIS]
GO
/****** Object:  UserDefinedFunction [dbo].[Character_Scramble]    Script Date: 07/06/2023 11:39:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[Character_Scramble]
(
    @OrigVal varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
 
-- Variables used
DECLARE @NewVal varchar(max);
DECLARE @OrigLen int;
DECLARE @CurrLen int;
DECLARE @LoopCt int;
DECLARE @Rand int;
 
-- Set variable default values
SET @NewVal = '';
SET @OrigLen = DATALENGTH(@OrigVal);
SET @CurrLen = @OrigLen;
SET @LoopCt = 1;
 
-- Loop through the characters passed
WHILE @LoopCt <= @OrigLen
    BEGIN
        -- Current length of possible characters
        SET @CurrLen = DATALENGTH(@OrigVal);
 
        -- Random position of character to use
        SELECT
            @Rand = Convert(int,(((1) - @CurrLen) * RandomValue + @CurrLen))
        FROM
            dbo.vwRandom;
 
        -- Assembles the value to be returned
        SET @NewVal = @NewVal + SUBSTRING(@OrigVal,@Rand,1);
 
        -- Removes the character from available options
        SET @OrigVal = Replace(@OrigVal,SUBSTRING(@OrigVal,@Rand,1),'');
 
        -- Advance the loop="color:black">
        SET @LoopCt = @LoopCt + 1;
    END
    -- Returns new value
    Return LOWER(@NewVal);
END
