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

前端 未结 5 608
渐次进展
渐次进展 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:24

    If you can afford/want to have a function in your database you could use something like:

    CREATE FUNCTION LEFTPAD
               (@SourceString VARCHAR(MAX),
                @FinalLength  INT,
                @PadChar      CHAR(1)) 
    RETURNS VARCHAR(MAX)
    AS
    BEGIN
      RETURN
        (SELECT Replicate(@PadChar, @FinalLength - Len(@SourceString)) + @SourceString)
    END
    

提交回复
热议问题