Trimming any Leading or trailing characters

2019-06-03 19:50发布

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

3条回答
仙女界的扛把子
2楼-- · 2019-06-03 20:12

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
查看更多
Bombasti
3楼-- · 2019-06-03 20:19

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...

查看更多
Melony?
4楼-- · 2019-06-03 20:28

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

Trim

TRIM ( [ characters FROM ] string )

查看更多
登录 后发表回答