USE gringlobal
GO

/****** Object:  UserDefinedFunction [dbo].[fn_redact_email_address]    Script Date: 9/14/2021 11:37:44 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
ALTER FUNCTION [dbo].[fn_redact_email_address] 
(
	@target_text NVARCHAR(255)
)
RETURNS NVARCHAR(255)
AS
BEGIN

DECLARE @email varchar(255)
DECLARE @target_index int, @start_index int, @end_index int
DECLARE @redacted_string NVARCHAR(20) = '[REDACTED]'

SET @target_index = CHARINDEX('@', @target_text)
IF (@target_index > 0)
	BEGIN
	   SET @end_index = @target_index
	   WHILE @end_index <= LEN(@target_text) AND 
			 SUBSTRING(@target_text, @end_index, 1) <> ' ' AND
			 SUBSTRING(@target_text, @end_index, 1) <> ',' AND
			 SUBSTRING(@target_text, @end_index, 1) <> ';' AND
			 SUBSTRING(@target_text, @end_index, 1) <> ')' AND
			 SUBSTRING(@target_text, @end_index, 1) <> '!'
		 BEGIN
			 SET @end_index = @end_index + 1
		 END

		SET @start_index = @target_index
		WHILE @start_index>=1 AND
			SUBSTRING(@target_text, @start_index-1, 1) <> ' ' AND
			SUBSTRING(@target_text, @start_index-1, 1) <> ',' AND
			SUBSTRING(@target_text, @start_index-1, 1) <> ';' AND
			SUBSTRING(@target_text, @start_index-1, 1) <> '(' AND
			SUBSTRING(@target_text, @start_index-1, 1) <> '!'
			BEGIN
				SET @start_index = @start_index - 1
			END
   
   SET @email = SUBSTRING(@target_text, @start_index, @end_index-@start_index)
   SET @target_text = replace(@target_text, @email, @redacted_string)
 END

RETURN @target_text
END
GO


