Skip to content
Advertisement

T-SQL: removing Time and Preceding characters from nvarchar column

I have a comments column in a SQL Server database table of type nvarchar and typically contains text along the lines of:

By: SoAndSo 01/01/2020 01:15:10 AM Blah Blah...

I am trying to find a way in the select statement to remove the character pattern of ‘#:#:# AM/PM’ and everything preceding it leaving me with “Blah Blah…”

In doing so I don’t want to remove legitimate uses of the work ‘AM’ because sometimes the comments were typed in caps. I tried using charindex but it doesn’t seem to allow you to specify patterns as specific as I am searching for. I end up losing legitimate uses of the work ‘am’.

Advertisement

Answer

You can use patindex() to find the pattern and then remove it using stuff():

select stuff(col, pos, pos + 22, '')
from (values ('By: SoAndSo 01/01/2020 01:15:10 AM Blah Blah')) t(col) cross apply
     (values (patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [AP]M%', col))) v(pos);

Edit: Based on your comment:

select stuff(col, 1, pos + 22, '')
from (values ('By: SoAndSo 01/01/2020 01:15:10 AM Blah Blah')) t(col) cross apply
     (values (patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [AP]M%', col))) v(pos);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement