改变列类型删除那些不能转换的

Alter column type deleting those that can't be converted

我需要将列的类型从 varchar(255) 更改为 uuid。我正在使用:

ALTER TABLE table_name
    ALTER COLUMN col TYPE UUID USING col::UUID;

但是如果该列中有一些值不是 uuid 格式,我将收到此错误: SQL Error [22P02]: ERROR: invalid input syntax for type uuid: "some_text"

是否可以删除那些具有无法转换为 uuid 的值的行?

使用@JuliusTuskenis 建议的 函数你可以简单地这样做:

ALTER TABLE table_name ALTER COLUMN col TYPE UUID USING uuid_or_null(col);
delete from table_name where col is null;

你必须先定义函数。

create function uuid_or_null(s text) returns uuid immutable AS
$$
begin
  return s::uuid;
exception when others then
  return null;
end;
$$ language plpgsql;

构建 uuid_or_null 的方式非常通用,或多或少是一种安全投射的模式 - 尝试投射,如果失败则做出相应反应。有几个 SO 线程在使用它。

您还可以预先清理 table,然后像这样更改列类型:

delete from table_name 
 where col !~* '^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$';
ALTER TABLE table_name ALTER COLUMN col TYPE UUID USING col::UUID;