How to convert int to char with leading zeros?

后端 未结 17 840
一生所求
一生所求 2020-12-12 18:55

I need to convert int datafield to nvarchar with leading zeros

example:

1 convert to \'001\'

867 convert to \'000867\', etc.

thx.


17条回答
  •  爱一瞬间的悲伤
    2020-12-12 19:06

    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).

提交回复
热议问题