February 24, 2005 at 5:56 pm
Hi all,
This could be a very simple question to you.
How to pad a 0 to left of string?
Say, I have a column (Char(5)), contains a string like '9876','1647'.... I want to pad a zero to those string <'10000'
Thank you.
February 24, 2005 at 6:30 pm
If your column is defined as char(5), then the data is actually going to be
'9876 ' or '1647 ' ** note trailing blanks
SQL automatically pads out CHAR fields with trailing spaces.
You could do something like this
CASE WHEN LEN(RTRIM([fieldname])) < 5 THEN RIGHT('00000' + RTRIM([fieldname]), 5) ELSE [fieldname] END
--------------------
Colt 45 - the original point and click interface
February 25, 2005 at 6:24 am
Or just simply
RIGHT('00000' + RTRIM([fieldname]), 5)
As you don't really care if it is already 5 it will be five either way when done.
February 25, 2005 at 7:10 am
May I ask why you store numbers in a CHAR(5) column anyway?
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
February 25, 2005 at 9:06 am
Hi Frank,
This situation comes up frequently in the U.S. where personal identification numbers assigned by the government (social security numbers) are always nine digits, and may begin with a zero. The numbers are an identifier, and are not used in computations. If the calling application happens to store the value in a numeric variable then the leading zero is often removed before storage in the DB.
Have a great day!
Wayne
February 28, 2005 at 2:26 am
Hm, yes, sure, there might be such valid reasons. However, I guess most of the time it is just laziness or something like that.
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy