如何在PostgreSQL中同时包含int和NULL值,如何从文本转换为int [英] How to cast from text to int if column contain both int and NULL values in PostgreSQL

查看:2106
本文介绍了如何在PostgreSQL中同时包含int和NULL值,如何从文本转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与标题相同。我有一列有一些文本值。例如,列数据1具有值('31',32','',NULL)。现在我想更新另一列说data2(类型INT)与data1的数据,所以我试图做这样的事情:

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).

问题是因为PostgreSQL不能将NULL或空值转换为INT。

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

推荐答案

实际上,你可以将 NULL 转换为int, int。假设如果 data1 包含空字符串或NULL,则在新列中需要NULL,您可以这样做:

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);

如果你想要一些其他的逻辑,你可以使用例如(空字符串转换为-1):

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;

这篇关于如何在PostgreSQL中同时包含int和NULL值,如何从文本转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆