I am trying to figure out how to be able to select/find and format each email address contained in a piece of text.
Example string:
Notification: Organizer must notify at least 30 days prior to the event. Provide the event information, including: day of contact information, location, date, schedule, activities, etc. Paul T. Hall – paulhall@email.com - Mikel Zubizarreta – mikelzubizarreta@email.com
The output of the string should be:
Notification: Organizer must notify at least 30 days prior to the event. Provide the event information, including: day of contact information, location, date, schedule, activities, etc. Paul T. Hall – <a href='mailto:paulhall@email.com'> - paulhall@email.com</a> - Mikel Zubizarreta – <a href='mailto:mikelzubizarreta@email.com'>mikelzubizarreta@email.com</a>
This are the attempts I have come up with:
Within a select:
, CASE
WHEN CHARINDEX('@',CONDITION) > 0 THEN
REPLACE(CONDITION, dbo.FN_GET_EMAIL_FROM_STRING(CONDITION), '<a href=''mailto:' + dbo.FN_GET_EMAIL_FROM_STRING(CONDITION) + '''>' + dbo.FN_GET_EMAIL_FROM_STRING(CONDITION) + '</a>')
ELSE CONDITION
END [CONDITION]
Contents of dbo.FN_GET_EMAIL_FROM_STRING(CONDITION):
ALTER FUNCTION [dbo].[FN_GET_EMAIL_FROM_STRING]
(
@TextContainingEmail VARCHAR(1000)
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @retval VARCHAR(1000);
SELECT TOP
1 @retval = Items
FROM
dbo.FN_SPLIT_STRING(@TextContainingEmail, '')
WHERE
Items LIKE '%@%';
RETURN @retval;
END;
Contents of: FN_SPLIT_STRING(@TextContainingEmail, '')
ALTER FUNCTION [dbo].[FN_SPLIT_STRING]
(
@STRING NVARCHAR(4000)
, @Delimiter CHAR(1)
)
RETURNS @Results TABLE(Items NVARCHAR(4000))
AS
BEGIN
DECLARE @INDEX INT;
DECLARE @SLICE NVARCHAR(4000);
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL ZERO FIRST TIME IN LOOP
SELECT @INDEX = 1;
IF @STRING IS NULL
RETURN;
WHILE @INDEX != 0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT
@INDEX = CHARINDEX(@Delimiter, LTRIM(RTRIM(@STRING)));
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX != 0
SELECT
@SLICE = LEFT(@STRING, @INDEX - 1);
ELSE
SELECT
@SLICE = @STRING;
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results
(
Items
)
VALUES(@SLICE);
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT
@STRING = REPLACE(RIGHT(@STRING, LEN(@STRING) - @INDEX), ',', '');
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0
BREAK;
END;
RETURN;
END;
But the output for the string I used as an example at the top of this post, ends up looking like this:
Notification: Organizer must notify at least 30 days prior to the event. Provide the event information, including: day of contact information, location, date, schedule, activities, etc. Paul T. Hall – <a href='mailto:paulhall@email.com'>paulhall@email.com</a> - Mikel Zubizarreta – mikelzubizarreta@email.com
As you can see, it sort of works but it only ads the 'mailto' tag to the first email address and not the second one.