I need to convert int datafield to nvarchar with leading zeros
example:
1 convert to \'001\'
867 convert to \'000867\', etc.
thx.
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).