Question

I have a query where I'm pulling in a check number from the database. The return value needs to always be 9 characters exactly. Most of the check numbers are only 6 characters, so I want to prepend 0s to to the string to ensure it is always exactly 9 characters. Since the check numbers can vary in length, it will be a different number of 0s for each one. What's the most efficient way to do this?

Était-ce utile?

La solution

If they're always between 6 and 9 digits, the easiest (and probably best) way to go is using CASE.

SELECT CASE WHEN LEN(CHECK_NUM)= 6 THEN '000' WHEN LEN(CHECK_NUM) = 7 THEN '00' 
       WHEN 
       LEN(CHECK_NUM) = 8 THEN '0' ELSE '' END + CHECK_NUM 
FROM   TABLE 

EDIT
In case the original values are numbers (int), try something like this:

SELECT CASE WHEN LEN(CHECK_NUM)= 6 THEN '000' WHEN LEN(CHECK_NUM) = 7 THEN '00' 
       WHEN 
       LEN(CHECK_NUM) = 8 THEN '0' ELSE '' END + CAST(CHECK_NUM AS VARCHAR(9)) 
FROM   TABLE1 

Take a look at the this SQL Fiddle.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top