Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

后端 未结 17 880
清歌不尽
清歌不尽 2020-11-22 08:13

I have a string that is up to 3 characters long when it\'s first created in SQL Server 2008 R2.

I would like to pad it with leading zeros, so if its original value w

17条回答
  •  孤街浪徒
    2020-11-22 08:41

    Although the question was for SQL Server 2008 R2, in case someone is reading this with version 2012 and above, since then it became much easier by the use of FORMAT.

    You can either pass a standard numeric format string or a custom numeric format string as the format argument (thank Vadim Ovchinnikov for this hint).

    For this question for example a code like

    DECLARE @myInt INT = 1;
    -- One way using a standard numeric format string
    PRINT FORMAT(@myInt,'D3');
    -- Other way using a custom numeric format string
    PRINT FORMAT(@myInt,'00#');
    

    outputs

    001
    001
    

提交回复
热议问题