'retrieve different format of date values with time from string (t-sql)

I have a requirement where i have to pull the date/time value from string but the problem is that they can be different formats because of which substring becomes more complicated.

Here's what i came up with but is there any other method where i could simply retreive dates of different format with time and convert them all in single format?

IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp (
    comments varchar(500)
   
)

insert into #temp (comments)
(
 select 'Mailed on 1/1/22 at 5 pm'
 union
 select 'Mailed on 01/2/2222 @ 6 am'
 union
 select 'Mailed on 01/2/22 in night'
 union
 select 'Mailed on 1/02/2222 at 4 pm'
 union
 select 'Mailed on 1/1/2222 at 4 pm'

);

select *
from #temp

cross apply (select PATINDEX('%Mailed On%',comments) as start_pos) as start_pos
cross apply (select case when substring(comments,patindex('%Mailed On%',comments)+9,11) like '%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%' then 1 
                         when substring(comments,patindex('%Mailed On%',comments)+9,8)  like '%[0-9][0-9]/[0-9]/[0-9][0-9]%' then 2
                         when substring(comments,patindex('%Mailed On%',comments)+9,10) like '%[0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%' then 3
                         when substring(comments,patindex('%Mailed On%',comments)+9,9)  like '%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%' then 4
                         when substring(comments,patindex('%Mailed On%',comments)+9,9)  like '%[0-9]/[0-9]/[0-9][0-9][0-9][0-9]%' then 5
                         when substring(comments,patindex('%Mailed On%',comments)+9,7)  like '%[0-9]/[0-9]/[0-9][0-9]%' then 6 else null end as substr) as substr
--cross apply (select case when substring(authcomments,start_pos + 9, 11) like '%[1-9]/[0123][0-9]/[0-9][0-9][0-9][0-9]%' then 1 else null end as substr)  as substr
cross apply (select case when substr = 1 then substring(comments,patindex('%Mailed On%',comments)+9,11) 
                         when substr = 2 then substring(comments,patindex('%Mailed On%',comments)+9,8)
                         when substr = 3 then substring(comments,patindex('%Mailed On%',comments)+9,10)
                         when substr = 4 then substring(comments,patindex('%Mailed On%',comments)+9,9)
                         when substr = 5 then substring(comments,patindex('%Mailed On%',comments)+9,9)
                         when substr = 6 then substring(comments,patindex('%Mailed On%',comments)+9,7)
                         else null end as maileddate
            )  as maileddate 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source