What is the best way to update a table by removing only one leading zero from numeric values in a column in SQL Server database

时间:2018-06-04 16:51:34

标签: sql sql-server

Currently, I have a column with 10 digits with leading '0' on all the records and I want to remove that '0' and keep 9 digits only even if it's start with a zero. I want to later join that table with another table in that column and the other table has 9 digits on all record and some start with 0.

3 个答案:

答案 0 :(得分:1)

If only the first digit is a 0 and the column is a numeric type you can convert it to int at the time of joining:

This will remove every 0 at the beginning

FROM table1 inner join table2 on CAST(table1.col as int) = table2.col

You can also substring it:

FROM table1 inner join table2 on substring(table1.col, 2, 9) = table2.col

Those two options are to be done at the moment of joining, however, you can just alter the table to update every value in the column if you convert the column's data type to int, but it will remove every 0 from the beginning, much like the first option:

ALTER TABLE table1
ALTER COLUMN col int;

答案 1 :(得分:0)

如果列是varchar并且始终有10个以0开头的数字?

然后RIGHT可能适合它。

declare @T1 table (id1 int identity(1,1) primary key, var_10 varchar(10));
insert into  @T1 (var_10) values ('0123456789');

declare @T2 table (id2 int identity(1,1) primary key, var_09 varchar(9));
insert into  @T2 (var_09) values ('123456789');

select * 
from @T1 t1
join @T2 t2 on t2.var_09 = right(t1.var_10, 9);

但如果您对此不太确定,那么我建议TRY_CONVERT(或TRY_CAST)将它们都归为INT。

select * 
from @T1 t1
join @T2 t2 on try_convert(int,t2.var_09) = try_convert(int,t1.var_10);

TRY_CONVERT对CONVERT有好处,如果某些数据不包含SQL不会在其上崩溃的数字。
但是f.e. CONVERT(int,'123FOOBAR')会导致SQL崩溃 而TRY_CONVERT(int,'123FOOBAR')只会返回NULL。

答案 2 :(得分:0)

如果您将它用于连接,则转换为int可能更有效

FROM table1 
inner join table2 
   on CAST(table1.col as int) = CAST(table2.col as int)