Search code examples
stringsortingcrystal-reportspad

Padding string with zeros in crystal report formula


I have some string whose max length cab be 4. But the leading zeros are not present so I need to pad the same in string from left. I am confused, as the string are like:

11A
12B
13
6
6A

Is there a way by which I can add leading zeros and then sort them, so that list can be like:

6
6A
11A
12B
13 and so on.

Update: I had tried using padding zeros from right and specifying the length like:

Right("00" & TableField,3) as maximum can be three, but that is sorting as

6
13
6A
11A
12B

Solution

  • The following is an example for retrieving the sorted data with an SQL Query.

    SELECT
        DATA
    FROM 
        (
            SELECT '11A' AS DATA
            UNION ALL
            SELECT '12B'
            UNION ALL
            SELECT '13'
            UNION ALL
            SELECT '6'
            UNION ALL
            SELECT '6A'
        ) AS TestTable
    ORDER BY
             LEN((
                    CASE WHEN ISNUMERIC(DATA) = 1
                        THEN LEFT(DATA + '0000', LEN(DATA) + 1)
                        ELSE DATA
                    END
                 )),
                 (
                    CASE WHEN ISNUMERIC(DATA) = 1
                        THEN LEFT(DATA + '0000', LEN(DATA) + 1)
                        ELSE DATA
                    END
                 )