tags:

views:

62

answers:

4

I have added a column to a table that will store a formatted string based on concatenating a number of other columns so I can search over it more easily. In order to save loading the whole table into another app and updating the new column then persisting, I want to write an UPDATE SQL query. But I can't figure out how to take an integer column and format it as in this example

Source column value = 1 Destination column value = 0001

I want the 3 leading zeros to be added in SQL.

Any ideas?

+5  A: 

Here's how to prepend seroes:

right('0000' + cast(MyColumn, nvarchar(4), 4)

This will concatenate 0000 with whatever value there is in MyColumn and return four rightmost characters.

Anton Gogolev
Very clever, Anton.
DOK
+2  A: 

Try this:

SELECT RIGHT('000'+ CONVERT(VARCHAR,Source),4) AS ColWithZeros
FROM Table
Nick Craver
+2  A: 
select Right( '0000' + cast( 1 as varchar),4)
klausbyskov
A: 

If it is coming from an integer column, I would remove the dependency on the string "0001".

Also, most of the other answers assume that 1 is the only data, I would suggest you need to find the number of digits, then add the appropriate number of zeroes. As it will fail with any aother data (10,20, 100 etc).

NimChimpsky
I believe that by taking the right-most 4 characters, the proposed solutions will handle any number of digits in the input.
DOK