如何在clickhouse中使用touint32orzero函数来改变列类型?

hgncfbus  于 2021-07-15  发布在  ClickHouse
关注(0)|答案(1)|浏览(561)

我在clickhouse表中有string列。我尝试用modify type将table改为uint32:

ALTER TABLE main.abonents
MODIFY COLUMN 
device_type UInt32 DEFAULT 0

但有错误:

Received exception from server:
Code: 6. DB::Exception: Received from 5.200.55.122:9000. DB::Exception: Cannot parse string 'mo' as UInt32: syntax error at begin of string. Note: there are toUInt32OrZero function, which returns zero instead of throwing exception..

很清楚,点击房屋使用 toUint32 对字符串执行类似“mobile”的函数并引发异常。以及使用函数的建议 toUInt32OrZero 转换类型。
我怎么用 toUInt32OrZero 带alter table的函数??

xienkqul

xienkqul1#

据我所知,没有这种办法。
你可以用第二张table来实现。让我们创建一个:

CREATE TABLE main.abonents_new AS main.abonents;

然后我们必须改变新表中的列。此表还没有数据,因此不会引发异常:

ALTER TABLE main.abonents_new MODIFY COLUMN device_type UInt32 DEFAULT 0;

然后,确保没有新数据写入main.abonents。在将数据传输到新表时,我们希望将所有内容都保留在适当的位置。
使用insert into select查询插入数据。确保列出所有具有相同顺序的字段;将设备类型 Package 到转换器函数( toUInt32OrZero ) :

INSERT INTO main.abonents_new SELECT field1, field2, ..., toUInt32OrZero(device_type) AS device_type, ..., fieldN FROM main.abonents;

然后,确保一切正常(行数相同,设备类型已按预期转换,等等),然后重命名表:

RENAME TABLE main.abonents TO main.abonents_old;
RENAME TABLE main.abonents_new TO main.abonents;

(或者,你可以 DROP 换成旧table;尽管我会保留旧数据,以便在情况恶化时能够恢复)

相关问题