Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Adding leading zeros to a varchar field

Author  Topic 

kohlhaas77
Starting Member

25 Posts

Posted - 2008-07-22 : 11:37:23
Hi Everyone...first of all, thanks in advance for anyone's help. :)

I am wanting to add leading zeros to a varchar field to make it 3-bytes in length. I am using the following syntax, but it is converting all values to '000'.

I am close, but no cigar...

RIGHT(REPLICATE('0',3) + CONVERT(VARCHAR(3),PART1.IPA_NBR),3)

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2008-07-22 : 11:48:52
This works OK for me. Post the data that you see it failing with.

select
PART1.IPA_NBR,
IPA_CHR =
right(replicate('0',3)+convert(varchar(3),PART1.IPA_NBR),3)
from
(
-- Test Data
select IPA_NBR = 1 union all
select 22 union all
select 333
) PART1

Results:
IPA_NBR IPA_CHR
----------- -------
1 001
22 022
333 333

(3 row(s) affected)



CODO ERGO SUM
Go to Top of Page

kohlhaas77
Starting Member

25 Posts

Posted - 2008-07-22 : 11:55:14
OK, like...

IPA_NBR Results
50 000
44 000
40 000
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2008-07-22 : 12:05:21
Too bad you didn't show the results you wanted.

CODO ERGO SUM
Go to Top of Page

kohlhaas77
Starting Member

25 Posts

Posted - 2008-07-22 : 12:08:09
050
044
040
Go to Top of Page

kohlhaas77
Starting Member

25 Posts

Posted - 2008-07-22 : 12:11:35
I got it...

RIGHT('000' + CONVERT(VARCHAR, PART1.IPA_NBR), 3
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-07-22 : 14:39:40
quote:
Originally posted by kohlhaas77

I got it...

RIGHT('000' + CONVERT(VARCHAR, PART1.IPA_NBR), 3



always remember to specify a length while casting to varchar.
Go to Top of Page
   

- Advertisement -