简体   繁体   中英

What is the best way to trim a string in T-SQL?

I want to trim a this character consist of a chinese character.

Select '10樓 10 /F'
Select '7樓 7/F'

Bad Result:

10樓 10 /F
7樓 7/F

I want to this:

10/F
7/F

You can use CHARINDEX to find the position of the chinese character.
Then use SUBSTRING to get the part you need based on that position.
And REPLACE all the spaces to nothing from that result.

For example:

select * , replace(substring(value, charindex(N'樓',value)+1, len(value)),' ','') as value2
from (values 
 (N'10樓 10 /F'),
 (N'7樓 7/F')
) v(value);

Note that putting the N before the strings marks them as NVARCHAR.
Since the chinese character is a unicode character.

Try to do this:

with cte as (
    select '10樓 10 /F' as t
    union all
    select '7樓 7/F'
)
select rtrim(ltrim(substring(t, charindex('樓', t) + 1, len(t)))) as t
from cte

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM