E
E
Eugene2015-10-09 18:10:44
SQL
Eugene, 2015-10-09 18:10:44

How to append '0' to the left of a string in a query under a certain condition?

There is a table with phone numbers. Some of the 5 characters, and others of 4. It is necessary to attach 0 to those of 4 at the beginning. Here I am looking for ways to do this. I can do it through the cursor, sorting through each line, but I thought maybe somehow I could get out of it through one UPDATE? Or something else optimally and beautifully.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artur Polozov, 2015-10-09
@tw1ggyz

just for the general case,
not only 4 digits, but also 3, 2 .. to the form 00XYZ
UPDATE Table SET
field = RIGHT('00000' + CAST( field AS varchar(5)), 5)
WHERE LEN(field) <= 5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question