How can I align a varchar field to the right in TS

2019-07-18 17:42发布

问题:

I have values like " 11(space)", "109", "X(space)(space)", "9(space)(space)", "15(space)" etc. in a column called MyCode that is varchar(3).

When I order them I have a prolbme like 11 appears before 109 when I ORDER them in ASC order.

I want to align the values to right by adding empty char in front so that ORDER would result:

 " 11"

 .. 

"109"

Question: How can I write my SELECT MyChar FROM MyTable so that for a value "1(space)(space)" it should return "(space)(space)1" etc. ?


@gbn: Your answer did what I needed but the output didnt change:

回答1:

Use this to always pad with leading spaces to a fixed length

SELECT RIGHT(
      SPACE(5) + 
      REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(MyChar), CHAR(160), ''), CHAR(9), ''), CHAR(10), ''), CHAR(13), '')
    , 5) AS Justified
FROM MyTable 
ORDER BY Justified

If you change one 5, you need to change both

Edit: added RTRIM

Edit 2: added hard space + other non-printable detection

What does this give you?

SELECT ASCII(RIGHT(MyChar, 1) FROM MyTable