|
Knowledge Base
Document information| Document ID: | 782 |
|---|
| Subject: | Padding leading zeros to an integer |
|---|
| Creation date: | 7/29/09 3:27 PM |
|---|
| Last modified on: | 7/29/09 3:28 PM |
|---|
Details
Assume that you an integer in your database that you want to pad with leading zeros to make it a fixed length column.
The table design is as follows.
create table Sample(id integer)
There are 4 rows in this table containing following values:
8
80
800
8000
Our goal is to write a query that will display the following results.
0008
0080
0800
8000
Following query will produce the results you like. This sample is
according to the syntax understood by Microsoft SQL Server. Modify the
functions appropriately if you are using any other database.
select CASE LEN(CAST(id as VARCHAR(5)))
WHEN 0 THEN '0000'
WHEN 1 THEN '000' + CAST(id as VARCHAR(5))
WHEN 2 THEN '00' + CAST(id as VARCHAR(5))
WHEN 3 THEN '0' + CAST(id as VARCHAR(5))
else CAST(id as VARCHAR(5))
END
From Sample
Add a comment to this document
Do you have a helpful tip related to this document that you'd like to share
with other users? Please add it below. Your name and tip will appear at the
end of the document text.
|