views:

155

answers:

4

Scenario:

I have a table1(col1 char(5)); A value in table1 may '001' or '01' or '1'.

Requirement:

Whatever value in col1, I need to retrive it in 5 char length concatenate with leading '0' to make it 5 char long.

Technique I applied:

select right(('00000' + col1),5) from table1; 

I didn't see any reason, why it doesn't work? but it didn't. Can anyone help me, how I can achieve the desired result?

+1  A: 

If you are storing the data in a CHAR field you are probably getting right spaces buffered with blanks. e.g. 01 = "01 ". If your do a RIGHT("00000" + value, 5) it'll still be the original value. You need to do a RTRIM() on the value or store the data in a VARCHAR field.

Zachary
Thank you zachary
mrp
A: 

The problem is that the char(5) field is always 5 characters long, not matter what you put into it. If you insert '01' into the field, the value stored is actually '01   ' (note the trailing spaces).

Try this:

select right(('00000' + replace(col1, ' ', '')), 5)

Edit: I will leave my answer here as an example, but Michael's answer using rtrim is better.

Ray
+10  A: 

Since you're using a fixed width column, it's already of size 5 (with whitespace). You need to trim it:

DECLARE @table1 TABLE (col1 char(5))

INSERT INTO @table1 (col1) VALUES ('12345')
INSERT INTO @table1 (col1) VALUES ('1')

SELECT RIGHT('00000'+RTRIM(col1),5) FROM @table1

-- Output:
-- 12345
-- 00001

Or use varchar instead:

DECLARE @table2 TABLE (col1 varchar(5))

INSERT INTO @table2 (col1) VALUES ('12345')
INSERT INTO @table2 (col1) VALUES ('1')

SELECT RIGHT('00000'+col1,5) FROM @table2

-- Output:
-- 12345
-- 00001
Michael Haren
Thank you Michael.
mrp
No problem. Here's another SQL Server gotcha you may run into, this time with `varchar` columns: if you don't spec a length, they default to 30. http://stackoverflow.com/questions/359257/why-is-the-default-length-for-varchar-30-when-using-cast
Michael Haren
+1 for not using REPLICATE ;-) example: http://stackoverflow.com/questions/3151503/tsql-scalar-function-need-to-return-a-concatenated-value/3151781#3151781
gbn
A: 

you need to store your data in a consistent manner, so you don't need to write queries to format the data each time. this will fix your existing data:

UPDATE table1
    SET col1= RIGHT('00000'+ISNULL(RTRIM(col1),''),5)

now every time you select you only have to do this:

SELECT col1 FROM table1

however, you must make sure that the data is formatted properly (leading zeros) every time it is inserted. I'd add a check constraint just to make sure:

ALTER TABLE table1 ADD CONSTRAINT
    CK_table1_col1 CHECK (LEN(col1)=5)

and when you insert do this:

INSERT INTO table1
        (col1, ...
    VALUES
        (RIGHT('00000'+ISNULL(RTRIM(@col1),''),5)
KM