How to convert a table column to another data type

ぃ、小莉子 提交于 2019-12-03 14:25:45

It sounds like the problem is that you have empty strings in your table. You'll need to handle those, probably with a case statement, such as:

execute %{ALTER TABLE "table1" ALTER COLUMN columnB TYPE integer USING CAST(CASE columnB WHEN '' THEN NULL ELSE columnB END AS INTEGER)}

Update: completely rewritten based on updated question.

NULLs shouldnt be a problem here. Tell us your postgresql version and your error message. Besides, why are you quoting identifiers ? Be aware that unquoted identifiers are converted to lowercase (default behaviour), so there might be a problem with your "columnB" in your query - it appears quoted first, unquoted in the cast.

Update: Before converting a column to integer, you must be sure that all you values are convertible. In this case, it means that columnB should contains only digits (or null). You can check this by something like

  select columnB from table where not columnB ~ E'^[0-9]+$';

If you want your empty strings to be converted to NULL integers, then run first

  UPDATE table set  columnB = NULL WHERE columnB = '';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!