Following query will create table2 with leading "0" for col1.
select '0' + Col1 Col1 into table2
from table1
If table2 is already created and you want to just populate data.
insert into table2(Col1)
select '0' + Col1
from table1
Question
I have a table named Table1 which has a varchar, named Col1. I want to create a Table2 and add a leading "0" in front of the contents of Col1.
How can I add a zero character to the front of a varchar? I have tried several ways but none seems to work.
Solution
Following query will create table2 with leading "0" for col1.
select '0' + Col1 Col1 into table2
from table1
If table2 is already created and you want to just populate data.
insert into table2(Col1)
select '0' + Col1
from table1
OTHER TIPS
Well, if you want to add 100 zeros, you can do:
select replicate('0', 100)+col1
. . .
If you want leading zeros with a given length, then combine this with right()
:
select right(replicate('0', 10)+col1, 10)
. . .
If you need to insert these into another table, use insert
or update
on that table instead of select
.
This should do what you want
insert into newTable select concat('0',col1), ........... FROM oldTable