I need to convert int datafield to nvarchar with leading zeros
example:
1 convert to \'001\'
867 convert to \'000867\', etc.
thx.
Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.
Example:
SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)
Result: '000867'
This work for me in MYSQL:
FUNCTION leadingZero(format VARCHAR(255), num VARCHAR(255))
RETURNS varchar(255) CHARSET utf8
BEGIN
return CONCAT(SUBSTRING(format,1,LENGTH(format)-LENGTH(num)),num);
END
For example:
leadingZero('000',999); returns '999'
leadingZero('0000',999); returns '0999'
leadingZero('xxxx',999); returns 'x999'
Hope this will help. Best regards
DECLARE @number1 INT, @number2 INT
SET @number1 = 1
SET @number2 = 867
-- Without the 'RTRIM', the value returned is 3__
!!!
SELECT RIGHT('000' + RTRIM(CAST(@number1 AS NCHAR(3)), 3 )) AS NUMBER_CONVERTED
-- Without the 'RTRIM', the value returned is 867___
!!!
SELECT RIGHT('000000' + RTRIM(CAST(@number2 AS NCHAR(6)), 6 )) AS NUMBER_CONVERTED
Works in SQLServer
declare @myNumber int = 123
declare @leadingChar varchar(1) = '0'
declare @numberOfLeadingChars int = 5
select right(REPLICATE ( @leadingChar , @numberOfLeadingChars ) + cast(@myNumber as varchar(max)), @numberOfLeadingChars)
Enjoy
Had same issue, this is how I resolved... Simple and elegant. The "4" is how long the string should be, no matter what length of integer is passed it will pad with zero's up to "4".
STUFF(SomeVariableOrField,1,0,REPLICATE('0',4 - LEN(SomeVariableOrField)))