简体   繁体   English

在T-SQL中修剪字符串的最佳方法是什么?

[英]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. 您可以使用CHARINDEX查找汉字的位置。
Then use SUBSTRING to get the part you need based on that position. 然后使用SUBSTRING根据该位置获得所需的零件。
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. 请注意,将N放在字符串之前会将其标记为NVARCHAR。
Since the chinese character is a unicode character. 由于汉字是Unicode字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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