I don't have much t-sql experience, but I came up with this function to pad 0's to the left of an nvarchar parameter passed in. The number of 0's padded to the left is based on the original length of the parameter passed in. I will explain each variable and then display my function. I tested it out and it does work, but I am curious if there are any refactorings or improvements I can make to it.
@number is the number passed into the function that will be padded
@result is the returned padded number -- the datatype for number is actually an nvarchar even though I call it number.
@maxLength is the maximum length all of the numbers must conform to. This is always 10.
@actualLength is the original length of the number passed into the function
@numOfZerosToPad is the @maxLength - @actualLength
As a side note, I have seen people do SELECT @variable = 1 and SET @variable = 1. Is there a difference to this or is it more a matter of taste?
Here is the function:
CREATE FUNCTION f_PadZerosToNumber
(
@number nvarchar(10)
)
RETURNS nvarchar(10)
AS
BEGIN
DECLARE @Result nvarchar(10)
DECLARE @maxLength int
SET @maxLength = 10
DECLARE @actualLength int
SET @actualLength = LEN(@number)
DECLARE @numOfZerosToPad int
SET @numOfZerosToPad = @maxLength - @actualLength
SET @Result = REPLICATE('0',@numOfZerosToPad) + @number
RETURN @Result
END
GO