you need to save your data in a consistent way, so you do not need to write queries to format the data every time. this will fix your existing data:
UPDATE table1 SET col1= RIGHT('00000'+ISNULL(RTRIM(col1),''),5)
Now every time you choose, you only need to do this:
SELECT col1 FROM table1
however, you must make sure that the data is formatted correctly (leading zeros) every time it is inserted. I would add a check constraint to make sure:
ALTER TABLE table1 ADD CONSTRAINT CK_table1_col1 CHECK (LEN(col1)=5)
and when you insert this:
INSERT INTO table1 (col1, ... VALUES (RIGHT('00000'+ISNULL(RTRIM(@col1),''),5)
KM.
source share