views:

3072

answers:

3

I have two fields in a table. One contains values such as BTA, BEA, REA. The other contains values such as 1,2,63,103.

I want to combine the 2 fields so they look like this BTA001, BTA002, BTA063, BTA103.

Notice how if the numbers are not 3 characters in length, I want to pad some 0's to the left of the number to make it equal to 3.

How would I go about doing this? The fields in the table are called Type which correspond to BTA, BEA, and REA and Id is the field that corresponds to 1, 2, 63, and 103.

+6  A: 
select Type + right('00' + cast(id as varchar(10)), 3)
from ...

Edit: if id can be null and you would like a zero to show, you can do:

select Type + right('00' + cast(isnull(id, 0) as varchar(10)), 3) 
from ...
RedFilter
What is the main difference between your answer and Learning's?
Xaisoft
Very little. I made the assumption you will always get a single-digit number out of the Id column, in which case you only need to prepend two zeros. CAST is ANSI-standard (thus portable), whereas CONVERT is SQL Server specific, but gives you more flexible conversion options.
RedFilter
What if the Id column can contain a null?
Xaisoft
Depends what about you want in that case. I edited my answer to provide an option. You may actually not want those rows at all in which case you should exclude them in the where clause
RedFilter
+1  A: 

select C1 + right(('000' + cast(C2 as nvarchar(10)),3) as

from t1

mson
+1  A: 

select FIELD1 + RIGHT('000' + CONVERT(VARCHAR,FIELD2), 3)

Learning
What is the difference between your implementation and OrbMan's?
Xaisoft