1

I am subtracting the date part from a string; sometimes there is an extra character at the end like here:

Mon,  1 Oct 2011 10:51:52 -0400%

Sometimes, the date is fine and does not have to be trimmed:

Mon,  21 Oct 2011 10:51:52 -0400

How do I remove this last character ( % in this example) in the case that the character does exist?

3
  • what column type are your dates being stored in? I don't think you would have this issue if it were stored in a datetime Commented Aug 24, 2015 at 17:27
  • it is actually an nvarchar. Commented Aug 24, 2015 at 17:41
  • Which DBMS are you using? Postgres? Oracle? Commented Aug 24, 2015 at 18:07

1 Answer 1

1

You can use REPLACE if you know the character.

REPLACE(@input, '%', '')

If you have a fixed format for everything before the additional character, you can use CHARINDEX to find the last ':', then get a SUBSTRING of the first character up to the known good characters (up to the -0400 in your case):

DECLARE @Input VARCHAR(50) = 'Mon,  1 Oct 2011 10:51:52 -0400%'
SELECT SUBSTRING(@Input, 1, LEN(@Input) - CHARINDEX(':', REVERSE(@Input)) + 9)

This returns:

Mon,  1 Oct 2011 10:51:52 -0400
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.