1

I have a table where I have some raw data. My requirement is to trim any leading or trailing spaces and operator characters in the given string column. Examples of operator characters include + - . > < = : ;"

Examples:

Value +Payment should be trimmed to Payment
Value ->300 Write should be trimmed to 300 Write

Shnugo
  • 66,100
  • 9
  • 53
  • 114
Rameshwar Pawale
  • 632
  • 3
  • 17
  • 35

3 Answers3

4

You can try this:

DECLARE @tbl TABLE(YourString VARCHAR(100));
INSERT INTO @tbl VALUES('+Payment'),('->300 Write'),('-:<Test,:%');

SELECT SUBSTRING(YourString,A.posFirst,A.posLast-A.posFirst+2)
FROM @tbl 
OUTER APPLY(SELECT PATINDEX('%[a-zA-Z0-9]%',YourString) AS posFirst
                  ,LEN(YourString)-PATINDEX('%[a-zA-Z0-9]%',REVERSE(YourString)) AS posLast) AS A

The result

Payment
300 Write
Test

You can add any allowed character to the pattern...

Shnugo
  • 66,100
  • 9
  • 53
  • 114
1

Try with PATINDEX

;WITH CTE
AS
(
    SELECT
       Val = '+Payment'
    UNION
    SELECT
       ' 300 Write'
)
SELECT
    *,
    NewVal = RTRIM(LTRIM(SUBSTRING(Val,PATINDEX('%[A-Z0-9]%',Val),LEN(Val))))
    FROM CTE
Jayasurya Satheesh
  • 7,826
  • 3
  • 22
  • 39
0

What version are you on. Trim will do characters on 2017 version.

Trim

TRIM ( [ characters FROM ] string )

paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/18808411) – CJM Feb 13 '18 at 12:21
  • 1
    @cjm How is this not an answer? It is a function that does exactly what the OP is asking. When I answered the version was not tagged. This answer could be valuable to user with 2017 or later. – paparazzo Feb 13 '18 at 12:25