PostgreSQL从值更新将空值视为文本

时间:2019-05-24 02:07:20

标签: postgresql psycopg2 executemany

当值的一列仅包含Null个值时,需要帮助解决问题。示例:

create table foo (
    id serial constraint foo_pk primary key,
    a int,
    b int
);

insert into foo (a,b) values (1, 1), (2, 2);

update foo t
set a = v.a, b = v.b
from (values (1, NULL, 1),(2, NULL, 2)) as v(id, a, b)
where v.id = t.id;

这给了我

[42804] ERROR: column "a" is of type integer but expression is of type text 
Hint: You will need to rewrite or cast the expression. Position: 22

我正在使用psycopg2.extras.execute_values来更新多个Django ORM对象。寻找不需要将null显式转换为字段类型的解决方案。

1 个答案:

答案 0 :(得分:0)

由于您为列a传递的所有值都是NULL s,因此Postgres将隐式认为它们是TEXT s

您有2个选项,

a表达式中将SET的值转换为int。

set a = v.a::int

OR

广播aINT的值之一,其他值默认为。

values (1, NULL::int, 1),(2, NULL, 2)) as v(id, a, b)

DEMO