HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How do I place leading zeros for numbers less than 10 without affecting those 10+?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
leadingzeroswithoutthoseplacenumbersthanlessforhow

Problem

Probably a newb question, but...

I have a table with a VARCHAR field containing numbers 1 through 300. I need to place a leading zero in front of any numbers less than 10 while retaining the original number if it is 10 or greater (i.e. 1=01, 10=10 and 300=300).

SELECT DISTINCT RIGHT('0'+CONVERT(VARCHAR,[FacilityCode]),3) FROM...


This returns 1=01, 10=010 and 300=300 (using the same examples as above)

EDIT: I'm trying to do this within a query so that I can do lookups without altering either table.

Can someone lend a brother a hand here? My brain just ain't working.

Solution

The safest way is probably to only add zeroes when the length of the column is 1 character:

UPDATE
   Table
SET
   MyCol = '0' + MyCol
WHERE
   LEN(MyCol) = 1;


This will cover all numbers under 10 and also ignore any that already have a leading 0.

EDIT

To just select the data try:

SELECT
   MyColPadded = CASE WHEN LEN(MyCol) = 1 THEN '0' + MyCol ELSE MyCol END
FROM
   MyTable;

Code Snippets

UPDATE
   Table
SET
   MyCol = '0' + MyCol
WHERE
   LEN(MyCol) = 1;
SELECT
   MyColPadded = CASE WHEN LEN(MyCol) = 1 THEN '0' + MyCol ELSE MyCol END
FROM
   MyTable;

Context

StackExchange Database Administrators Q#72277, answer score: 12

Revisions (0)

No revisions yet.