PadLeft function in T-SQL

后端 未结 17 2837
挽巷
挽巷 2020-11-27 03:44

I have the following table A:

id
----
1
2
12
123
1234

I need to left-pad the id values with zero\'s:

id
----
0         


        
17条回答
  •  Happy的楠姐
    2020-11-27 04:13

    Something fairly ODBC compliant if needed might be the following:

    select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
            + cast (FIELD as varchar(10))
      from TABLE_NAME
    

    This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.

提交回复
热议问题