LTRIM与RTRIM函数意外修剪多余字符的问题咨询
问题
原字符串:
morning is here sunshine is here the sky is clear the morning is here
执行以下SQL语句:
ltrim('morning is here sunshine is here the sky is clear the morning is here', 'morning is here') rtrim('morning is here sunshine is here the sky is clear the morning is here', 'morning is here')
得到的输出结果:
ltrim -- unshine is here the sky is clear the morning is here rtrim -- morning is here sunshine is here the sky is clea
为何会有额外字符被修剪掉?
解答
SQL中的ltrim和rtrim函数并非按整个字符串匹配修剪,而是根据你传入的第二个参数里的单个字符集合来处理:
对于
ltrim:你指定的修剪字符集是'morning is here',包含的字符有m、o、r、n、i、g、空格、s、h、e。原字符串开头的morning is here(注意末尾有空格)被修剪后,接下来的字符是s,而s正好在修剪字符集内,所以也被剪掉,最终剩下的内容从u开始,变成了unshine...。对于
rtrim:修剪字符集里包含r,原字符串结尾的morning is here被修剪完毕后,往前看是clear的最后一个字符r,r属于修剪字符集,因此也被剪掉,导致clear变成了clea。
总结:这两个函数会从字符串的开头/结尾逐个检查字符,只要字符在指定的集合里就会被修剪,直到遇到不在集合里的字符才停止,并非匹配整个子串进行修剪。
内容的提问来源于stack exchange,提问作者Kinjal Brahmbhatt
相关产品推荐
相关产品推荐

