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

后端 未结 17 1276
清歌不尽
清歌不尽 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:26

    I came here specifically to work out how I could convert my timezoneoffset to a timezone string for converting dates to DATETIMEOFFSET in SQL Server 2008. Gross, but necessary.

    So I need 1 method that will cope with negative and positive numbers, formatting them to two characters with a leading zero if needed. Anons answer got me close, but negative timezone values would come out as 0-5 rather than the required -05

    So with a bit of a tweak on his answer, this works for all timezone hour conversions

    DECLARE @n INT = 13 -- Works with -13, -5, 0, 5, etc
    SELECT CASE 
        WHEN @n < 0 THEN '-' + REPLACE(STR(@n * -1 ,2),' ','0') 
        ELSE '+' + REPLACE(STR(@n,2),' ','0') END + ':00'
    

提交回复
热议问题