Ticket #2329: fn_redact_email_address.sql

File fn_redact_email_address.sql, 1.7 KB (added by Benjamin Haag, 5 years ago)
Line 
1USE gringlobal
2GO
3
4/****** Object: UserDefinedFunction [dbo].[fn_redact_email_address] Script Date: 9/14/2021 11:37:44 AM ******/
5SET ANSI_NULLS ON
6GO
7
8SET QUOTED_IDENTIFIER ON
9GO
10
11
12-- =============================================
13-- Author: <Author,,Name>
14-- Create date: <Create Date, ,>
15-- Description: <Description, ,>
16-- =============================================
17ALTER FUNCTION [dbo].[fn_redact_email_address]
18(
19 @target_text NVARCHAR(255)
20)
21RETURNS NVARCHAR(255)
22AS
23BEGIN
24
25DECLARE @email varchar(255)
26DECLARE @target_index int, @start_index int, @end_index int
27DECLARE @redacted_string NVARCHAR(20) = '[REDACTED]'
28
29SET @target_index = CHARINDEX('@', @target_text)
30IF (@target_index > 0)
31 BEGIN
32 SET @end_index = @target_index
33 WHILE @end_index <= LEN(@target_text) AND
34 SUBSTRING(@target_text, @end_index, 1) <> ' ' AND
35 SUBSTRING(@target_text, @end_index, 1) <> ',' AND
36 SUBSTRING(@target_text, @end_index, 1) <> ';' AND
37 SUBSTRING(@target_text, @end_index, 1) <> ')' AND
38 SUBSTRING(@target_text, @end_index, 1) <> '!'
39 BEGIN
40 SET @end_index = @end_index + 1
41 END
42
43 SET @start_index = @target_index
44 WHILE @start_index>=1 AND
45 SUBSTRING(@target_text, @start_index-1, 1) <> ' ' AND
46 SUBSTRING(@target_text, @start_index-1, 1) <> ',' AND
47 SUBSTRING(@target_text, @start_index-1, 1) <> ';' AND
48 SUBSTRING(@target_text, @start_index-1, 1) <> '(' AND
49 SUBSTRING(@target_text, @start_index-1, 1) <> '!'
50 BEGIN
51 SET @start_index = @start_index - 1
52 END
53
54 SET @email = SUBSTRING(@target_text, @start_index, @end_index-@start_index)
55 SET @target_text = replace(@target_text, @email, @redacted_string)
56 END
57
58RETURN @target_text
59END
60GO
61
62