Most efficient method for adding leading 0's to an int in sql

前端 未结 5 528
渐次进展
渐次进展 2021-02-05 17:58

I need to return two fields from a database concatenated as \'field1-field2\'. The second field is an int, but needs to be returned as a fixed length of 5 with leading 0\'s. T

5条回答
  •  青春惊慌失措
    2021-02-05 18:28

    That is pretty much the way: Adding Leading Zeros To Integer Values

    So, to save following the link, the query looks like this, where #Numbers is the table and Num is the column:

       SELECT RIGHT('000000000' + CONVERT(VARCHAR(8),Num), 8) FROM #Numbers
    

    for negative or positive values

    declare @v varchar(6)
    select @v = -5
    
    SELECT case  when @v < 0 
    then '-' else '' end + RIGHT('00000' + replace(@v,'-',''), 5) 
    

提交回复
热议问题