sql - 当我使用 CASE 将字段设置为 NULL 时,为什么 PostgreSQL 会提示类型?

标签 sql postgresql sql-update

我有以下查询:

UPDATE managed_avs 
     SET own_license_expires_at = CASE id WHEN 50 THEN NULL END 
WHERE id in (50)

我收到以下错误:

ERROR:  column "own_license_expires_at" is of type timestamp without time zone but expression is of type text
LINE 1: update managed_avs set own_license_expires_at = CASE id WHEN...
                                                        ^
HINT:  You will need to rewrite or cast the expression.

为什么说 CASE id WHEN 50 THEN NULL END 是文本类型?不就是 NULL 吗?

最佳答案

发生这种情况是因为 case 表达式为每个可能的结果返回一个 null 值。由于 null 值没有类型,Postgres 默认为 text

您可以使用 pg_typeof() 验证:

select pg_typeof(case id when 50 then null end)
from (values (50) ) as x (id);

返回

pg_typeof
---------
text     

为了使其工作,when 的结果需要转换为时间戳或整个表达式:

case id when 50 then null::timestamp end

(case id when 50 then null end)::timestamp

关于sql - 当我使用 CASE 将字段设置为 NULL 时,为什么 PostgreSQL 会提示类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42061872/

相关文章:

sql - PostgreSQL 选择主记录并显示特定记录的详细信息列

sql - 在 PostgreSQL 中搜索名称

Mysql更新和连接查询

mysql - 从表列表中选择相同的列

sql - PostgreSQL。如何在递归查询中为所有 child 保存第一个 ID?

sql - Oracle SQL解析器

sql - 列的不同值

java - 使用 Postgres 8.2 时出现错误 : operator does not exist: integer = character varying,

mysql - 错误的 MySQL 更新查询后恢复?

mysql - 如何在所有行中使用不同的值更新列?