首先自定义两个函数,其中try_cast_numeric函数是将字符类型转成数字类型,try_cast_timestamp函数是将字符类型转成时间戳类型。
create or replace function try_cast_numeric(p_in text, p_default numeric default null)
returns numeric
as
$$
begin
begin
return $1::numeric;
exception
when others then
return p_default;
end;
end;
$$
language plpgsql;
create or replace function try_cast_timestamp(p_in text, p_default timestamp default null)
returns timestamp
as
$$
begin
begin
return $1::timestamp;
exception
when others then
return p_default;
end;
end;
$$
language plpgsql;
有了以上两个函数就可以使用以下脚本进行列类型转换,并且可以将无法转换的值设置成默认值NULL。
alter table ccf.newtable alter column1 type int using try_cast_numeric(column1)