我在 PostgreSQL 表中有 2 列。该mac_address_temp
列用于从字符类型迁移到 MAC 地址类型:
mac_address | macaddr |
mac_address_temp | character varying(17) |
Run Code Online (Sandbox Code Playgroud)
我想将数据从 mac_address_temp 迁移到 mac_address,但有些数据无法转换为macaddr
类型。
mac_address | mac_address_temp
-------------+------------------
| AAB5:4f27:e299
| AAB54f27e299
UPDATE mactable SET mac_address = CAST(mac_address_temp as macaddr);
ERROR: invalid input syntax for type macaddr: "AAB5:4f27:e299"
Run Code Online (Sandbox Code Playgroud)
有没有办法忽略CAST
不工作的地方并仍然更新表格的其余部分?
只需删除 ':' 字符,更新将起作用:
UPDATE mactable SET mac_address = CAST(replace(mac_address_temp,':','') as macaddr);
Run Code Online (Sandbox Code Playgroud)
要摆脱所有不是十六进制数字的内容:
postgres=# insert into mactable (mac_address_temp) values ('AAB5:-4f-27:e2-99');
INSERT 0 1
postgres=# select regexp_replace(mac_address_temp, '[^a-fA-F0-9]', '', 'g')
postgres-# from mactable;
regexp_replace
----------------
AAB54f27e299
AAB54f27e299
(2 rows)
postgres=#
Run Code Online (Sandbox Code Playgroud)
所以更新将是:
UPDATE mactest SET mac_address = CAST(regexp_replace(mac_address_temp, '[^a-fA-F0-9]', '', 'g') as macaddr);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4929 次 |
最近记录: |