How to cast from text to int if column contain both int and NULL values in PostgreSQL

时光总嘲笑我的痴心妄想 提交于 2019-12-11 04:38:21

问题


As in title. I have one column which has some text values. For example column data1 has values ('31',32','',NULL). Now I want to update another column say data2 (type INT) with data from data1, so I am trying to do something like that:

UPDATE table SET data2=CAST(data1 AS INT).

The problem is because PostgreSQL cannot cast NULL or empty values to INT.


回答1:


Actually, you can cast NULL to int, you just can't cast an empty string to int. Assuming you want NULL in the new column if data1 contains an empty string or NULL, you can do something like this:

UPDATE table SET data2 = cast(nullif(data1, '') AS int);

If you want some other logic, you can use for example (empty string converts to -1):

UPDATE table SET data2 = CASE WHEN data1 = '' THEN -1 ELSE cast(data1 AS int) END;


来源:https://stackoverflow.com/questions/4626346/how-to-cast-from-text-to-int-if-column-contain-both-int-and-null-values-in-postg

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