当我使用CASE将字段设置为NULL时,为什么PostgreSQL会抱怨类型?

时间:2017-02-06 06:49:55

标签: 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

1 个答案:

答案 0 :(得分:2)

这是因为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
相关问题