tags:

views:

697

answers:

4

I need to return two fields from a database concatenated as 'field1-field2'. The second field is an int, but needs to be returned as a fixed length of 5 with leading 0's. The method i'm using is:

SELECT Field1 + '-' + RIGHT('0000' + CAST(Field2 AS varchar),5) FROM ...

Is there a more efficient way to do this?

+10  A: 

That is pretty much the way: Adding Leading Zeros To Integer Values

So, to save following the link, the query looks like this, where #Numbers is the table and Num is the column:

   SELECT RIGHT('000000000' + CONVERT(VARCHAR(8),Num), 8) FROM #Numbers

for negative or positive values

declare @v varchar(6)
select @v = -5

SELECT case  when @v < 0 
then '-' else '' end + RIGHT('00000' + replace(@v,'-',''), 5)
SQLMenace
What about negative numbers?
Dems
This will generate an exception with a number due to conversions, you need the cast
Mitchel Sellers
I added some code that will do negative or positive values
SQLMenace
Actually it doesn't generate an exception because it converts the '000000' to a int and does an add - still doesn't work though
DJ
added the convert
SQLMenace
A: 

I would do it like this.

SELECT RIGHT(REPLICATE('0', 5) + CAST(Field2 AS VARCHAR(5),5)

Not necessarily all that "Easier", or more efficient, but better to read. Could be optimized to remove the need for "RIGHT"

Mitchel Sellers
+1  A: 

If you can afford/want to have a function in your database you could use something like:

CREATE FUNCTION LEFTPAD
           (@SourceString VARCHAR(MAX),
            @FinalLength  INT,
            @PadChar      CHAR(1)) 
RETURNS VARCHAR(MAX)
AS
BEGIN
  RETURN
    (SELECT Replicate(@PadChar, @FinalLength - Len(@SourceString)) + @SourceString)
END
Petros
+1  A: 

Another way (without CAST or CONVERT):

SELECT RIGHT(REPLACE(STR(@NUM),' ','0'),5)
DJ