USE [HRISDEV]
GO

/****** Object:  UserDefinedFunction [dbo].[func_mask_string_v2]    Script Date: 06/06/2023 08:19:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




-- Mask string, except for first & last char
-- by Pribadi Pamungkas. 2020-05-16

CREATE FUNCTION [dbo].[func_mask_string_v2]
(
	@pi_string VARCHAR(200),
	@pi_mask_char CHAR(1)
)
RETURNS VARCHAR(200)
AS
BEGIN

	DECLARE
		@string VARCHAR(200),
		@mask_char CHAR(1),
		@result VARCHAR(200),
		@posisi INT = 0,
		@startpos INT = 0,
		@endpos INT,
		@lastpos INT = 0

	IF COALESCE(@pi_mask_char, '') = '' SET @mask_char = 'x'

	SET @string = LTRIM(RTRIM(COALESCE(@pi_string, '')))

	IF LEN(@string) > 2
		BEGIN

			DECLARE @midstring VARCHAR(200)

			SET @midstring = SUBSTRING(@string, 2, LEN(@string)-2)

			SET @result = @midstring
			SET @midstring = @midstring + '.'
			WHILE (PATINDEX('%[^a-zA-Z0-9]%', @midstring) <> 0)
				BEGIN 
					SET @posisi = PATINDEX('%[^a-zA-Z0-9]%', @midstring)
					SET @midstring = STUFF(@midstring, @posisi, 1, 'a') 

					IF @posisi = 0
						SET @endpos = LEN(@midstring)
					else
						SET @endpos = @posisi - 1
		
					SET @startpos = @lastpos + 1
					IF (@endpos-@startpos+1) <> 0
						SET @result = STUFF(@result, @startpos, (@endpos-@startpos+1), REPLICATE('x', (@endpos-@startpos+1))) 
					SET @lastpos = @posisi
				END 
			SET @result = LEFT(@string, 1) + @result + RIGHT(@string, 1)
		END
	ELSE
		SET @result = @pi_string

	RETURN @result

END
GO


