PadLeft function in T-SQL

后端 未结 17 2826
挽巷
挽巷 2020-11-27 03:44

I have the following table A:

id
----
1
2
12
123
1234

I need to left-pad the id values with zero\'s:

id
----
0         


        
17条回答
  •  时光取名叫无心
    2020-11-27 04:13

    I created a function to do this, where you can specify the desired output character length:

    CREATE FUNCTION [dbo].[udfLeadingZero]
    (
            @String VARCHAR(MAX)
    ,       @Len INT
    )
    RETURNS VARCHAR(MAX)
    BEGIN
        SET @String = RIGHT(REPLICATE('0',@Len)+@String,@Len)
    RETURN @String
    END
    GO
    

    Example results

提交回复
热议问题