Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Left Padding in TSQL 2

Status
Not open for further replies.

MMund

Programmer
Oct 9, 2007
57
CA
Does anyone know of a non-kludgy way in TSQL to left-pad zeros onto a numeric field to export into an SDF file?

For example,
45000 would show in the SDF file as 00045000 and 1500 would show as 00001500.

I am making the switch from FoxPro 2.6 to TSQL. In FoxPro, I had the PADL function that handled this with ease. In TSQL, I don't see anything like that.
 
Say your total length in characters is 10. The following code will pad an INT to create a string of 10 characters:

LEFT('0000000000' + CONVERT(VARCHAR(10), YourIntColumn), 10)
 
This code alows for any legth.. I you are using ints then you can convert as in RiverGuys's code
Code:
declare @var as varchar(10)
set @var = '45000'
select right(Replicate('0',8 - Len(@var)) + @var,8)
 
Actually to allow it to be more flexible and allow for any length you want, try this:
Code:
declare @var as varchar(10)
declare @len as int

set @var = '45000'
set @len = 8

select right(Replicate('0',@len - Len(@var)) + @var,@len)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top