3

How can I add zeros to SQL column to match 9 digits? We have an column name SystemID which contains products IDs. Our CRM system removes zeros automatically but sometimes we need to take out those numbers and paste to Excel and it needs to includes all numbers. It's something like this:

ID1111111
ID111111
ID11111

How can I add zeros after 6 digits?

If ID111111 then ID1111011
If ID22222  then ID2222002
If ID3333   then ID3333000
4
  • 3
    The IDs after adding zeroes don't look like the original IDs. Can you explain what is happening here? Commented Feb 14, 2017 at 7:35
  • ID is always 9 digits but our software removes zeros automaticly but I need to add those zeros again when running select so I need to add zeros after 6 so: if ID1111 so ID111001 and if ID222222 then ID2222202 Commented Feb 14, 2017 at 7:43
  • Maybe this is what you're looking for :-) sql server 2008 add to string in particular position within name column Commented Feb 14, 2017 at 7:47
  • 3
    Your sample data is very unclear. Can you please clean up your question so we don't have to keep guessing? Commented Feb 14, 2017 at 7:55

3 Answers 3

1

Your description is not all clear, but it might be this you are looking for:

DECLARE @Dummy TABLE(YourID VARCHAR(100));
INSERT INTO @Dummy VALUES('ID111111 '),('ID22222'),('ID3333')      

SELECT LEFT(STUFF(YourID + REPLICATE('0',9),7,0,REPLICATE('0',9-LEN(YourID))),9)
FROM @Dummy

The result

ID1111011
ID2222002
ID3333000

Short explanation

First I add 9 zeros to make sure, that the original string has got 9 digits in any case. Then I use STUFF to introduce the appropriate number of zeros in the 7th place. The final string is cut at 9.

Sign up to request clarification or add additional context in comments.

Comments

1
DECLARE @Test TABLE(YourID VARCHAR(100));
INSERT INTO @Test VALUES('ID111111'),('ID22222'),('ID3333'),('ID'),('ID1234567')

SELECT LEFT(YourID, 6) + REPLICATE('0', 9 - LEN(YourID)) + SUBSTRING(YourID, 7, LEN(YourID))

FROM @Test

Comments

0

You can use a combination of padding and substring to get the output you want:

SELECT LEFT(SUBSTRING(SystemID, 1, 6) + '000', 15 - LEN(SystemID)) +
           SUBSTRING(SystemID, 7, LEN(SystemID) AS SystemIDPadded
FROM yourTable

2 Comments

but i need to add zeros after 6 digits to be 9. So if SystemID is ID11111 (7 digits) i need to add zeros after 6 so ID1111001 and if systemID 8 digits so I need ID2222202
@DavidJackowiak I gave you a query which works for the example in your comment above. Not sure about the general case though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.