简体   繁体   English

删除尾随空格并将其添加为前导空格

[英]Remove trailing spaces and add them as leading spaces

I would like to remove the trailing spaces from the expressions in my column and add them to beginning of the expression. 我想从列中的表达式中删除尾随空格,并将其添加到表达式的开头。 So for instance, I currently have the expressions: 因此,例如,我目前有以下表达式:

Sample_four_space    
Sample_two_space  
Sample_one_space 

I would like to transform this column into: 我想将此列转换为:

    Sample_four_space
  Sample_two_space
 Sample_one_space

I have tried this expression: 我已经尝试过以下表达式:

UPDATE My_Table
SET name = REPLACE(name,'% ',' %')

However, I would like a more robust query that would work for any length of trailing spaces. 但是,我想要一个更健壮的查询,该查询适用于任何长度的尾随空格。 Can you help me develop a query that will remove all trailing spaces and add them to the beginning of the expression? 您能帮我开发一个查询,以删除所有尾随空格并将其添加到表达式的开头吗?

If you know all spaces are at the end (as in your example, then you can count them and put them at the beginning: 如果您知道所有空格都在末尾(如您的示例中所示,那么您可以算出它们并将其放在开头:

select concat(space(length(name) - length(replace(name, ' ', ''))),
              replace(name, ' ', '')
             )

Otherwise the better solution is: 否则,更好的解决方案是:

select concat(space( length(name) - length(trim(trailing ' ' from name)) ),
              trim(trailing ' ' from name)
             )

or: 要么:

select concat(space( length(name) - length(rtrim(name)) ),
              rtrim(name)
             )

Both these cases count the number of spaces (in or at the end of). 这两种情况都计算空格数(在空格中或结尾)。 The space() function then replicates the spaces and concat() puts them at the beginning. 然后, space()函数将复制空格并将concat()放在开头。

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

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