-3

My number needs to be 8 digits long, however If its less than 8 digits long I need to add trailing zeros to the it.

  • Example: 1234
  • Desired result: 12340000

I tried this at first:

DECLARE @YourNumber VARCHAR(8)=1234567;
SELECT DISTINCT 
LEFT('00000000'+CAST(ISNULL(@YourNumber,0) AS VARCHAR),8)  

However the result is: 00000000

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rafa N
  • 1
  • 1

4 Answers4

2

I have the same read as @Hogan +1. I just tend to opt for concat(). No need to test for nulls or even care if the value is a string or int

Example

Select IfInt = left(concat(1234  ,'00000000'),8)
      ,IfStr = left(concat('1234','00000000'),8)
      ,IfNull= left(concat(null  ,'00000000'),8) 

Results

IfInt       IfStr       IfNull
12340000    12340000    00000000
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
0

If what you are asking for is actually what you want then try this:

DECLARE @YourNumber VARCHAR(8)='1234567';
SELECT DISTINCT 
LEFT(CAST(ISNULL(@YourNumber,0) AS VARCHAR)+'00000000',8)  
Hogan
  • 69,564
  • 10
  • 76
  • 117
0

Since you are starting with a "number" in a string (DECLARE @YourNumber VARCHAR(8)=1234567;) there is no need to use cast. You can simply add the required number of zeroes:

DECLARE @YourNumber VARCHAR(8)= '1234567'; -- Using a string rather than an   Int  literal.
select @YourNumber + Replicate( '0', 8 - Len( @YourNumber ) ) as PaddedString;

Aside: It is a best practice to always specify the length of strings, i.e. CAST(ISNULL(@YourNumber,0) AS VARCHAR(8)).

HABO
  • 15,314
  • 5
  • 39
  • 57
-2

All you have to do is move the "+ '00000000'" portion of the code to the right side of the Cast Function.

DECLARE @YourNumber VARCHAR(8)=1234567;
SELECT DISTINCT 
LEFT(CAST(ISNULL(@YourNumber,0) AS VARCHAR)+'00000000',8)

Resulting in final value of: 12345670

Dale K
  • 25,246
  • 15
  • 42
  • 71
Rafa N
  • 1
  • 1
  • 2
    This won't work since 1234567 is not a varchar constant. How exactly is this different than the answer I posted 20 mins ago? – Hogan Jan 19 '23 at 20:48
  • 1
    It isn't I just did not see your answer, so I decided to post the solution myself. – Rafa N Jan 19 '23 at 21:07