How to convert int to char with leading zeros?

后端 未结 17 834
一生所求
一生所求 2020-12-12 18:55

I need to convert int datafield to nvarchar with leading zeros

example:

1 convert to \'001\'

867 convert to \'000867\', etc.

thx.


17条回答
  •  执念已碎
    2020-12-12 19:20

    One line solution (per se) for SQL Server 2008 or above:

    DECLARE @DesiredLenght INT = 20;
    SELECT 
        CONCAT(
            REPLICATE(
                '0',
                (@DesiredLenght-LEN([Column])) * (1+SIGN(@DesiredLenght-LEN([Column])) / 2) ),
            [Column])
    FROM Table;
    

    Multiplication by SIGN expression is equivalent to MAX(0, @DesiredLenght-LEN([Column])). The problem is that MAX() accepts only one argument...

提交回复
热议问题