我有以下查询:
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/