I need to convert int datafield to nvarchar with leading zeros
example:
1 convert to \'001\'
867 convert to \'000867\', etc.
thx.
I found a good article here:
Padding a string with leading zeros
I've need to do this a lot of times when outputing a fixed length data export where for instance a numeric column is 9 characters long and you need to prefix with leading 0's.
Using RIGHT
is a good option but you can also do the following:
SUBSTRING(CAST((POWER(10, N) + value) AS NVARCHAR(N + 1)), 2, N)
where N
is the total number of digits you want displayed. So for a 3-digit value with leading zeros (N = 3
):
SUBSTRING(CAST((POWER(10, 3) + value) AS NVARCHAR(4)), 2, 3)
or alternately
SUBSTRING(CAST(1000 + value) AS NVARCHAR(4)), 2, 3)
What this is doing is adding the desired value to a power of 10 large enough to generate enough leading zeros, then chopping off the leading 1.
The advantage of this technique is that the result will always be the same length, allowing the use of SUBSTRING
instead of RIGHT
, which is not available in some query languages (like HQL).
Try this: select right('00000' + cast(Your_Field as varchar(5)), 5)
It will get the result in 5 digits, ex: 00001,...., 01234
Not to High-Jack this question but the note needs to be made that you need to use (N)VARCHAR instead of (N)CHAR data-type.
RIGHT('000' + CAST(@number1 AS NCHAR(3)), 3 )
Above segment, will not produce the correct response from SQL 2005
RIGHT('000' + CAST(@number1 AS NVARCHAR(3)), 3 )
Above segment, will produce the desired response from SQL 2005
The the varchar will provide you with the desired prefix length on the fly. Where as the fixed length data type will require length designation and adjustments.
Data type "int" cannot be more than 10 digits, additionally the "Len()" function works on ints, so there's no need to convert the int to a string before calling the len() function.
Lastly, you are not taking into account the case where the size of your int > the total number of digits you want it padded to (@intLen).
Therefore, a more concise / correct solution is:
CREATE FUNCTION rf_f_CIntToChar(@intVal Int, @intLen Int) RETURNS nvarchar(10)
AS
BEGIN
IF @intlen > 20 SET @intlen = 20
IF @intlen < LEN(@intVal) RETURN RIGHT(CONVERT(nvarchar(10), @intVal), @intlen)
RETURN REPLICATE('0', @intLen - LEN(@intVal)) + CONVERT(nvarchar(10), @intVal)
END
select right('000' + convert(varchar(3),id),3) from table
example
declare @i int
select @i =1
select right('000' + convert(varchar(3),@i),3)
BTW if it is an int column then it will still not keep the zeros Just do it in the presentation layer or if you really need to in the SELECT