[英]Case return null when result query is empty
I try to initialize variable from table, but when result of query returns 0 row case expression is not working, for example:我尝试从表中初始化变量,但是当查询结果返回 0 行时,case 表达式不起作用,例如:
do $$
declare _reportId bigint := null;
_serviceId bigint := null;
begin
_serviceId := 12;
_reportId := null;
select case when _serviceId is null then rp.value::bigint else _serviceId end
into _serviceId
from rep.reportparameters as rp
where rp.reportid = _reportId;
RAISE NOTICE '%', _serviceId;
end;
$$;
So in this variant of parameters i need _serviceId
value 12 (because result of query returns 0 row, is no reportId with null in table).因此,在这种参数变体中,我需要
_serviceId
值 12(因为查询结果返回 0 行,表中没有 reportId 为 null)。 But i have null
value for _serviceId
但我的
_serviceId
为null
值
Analog construction in SQL Server work great, they return 12 for @serviceId
: SQL Server 中的模拟构造工作得很好,它们为
@serviceId
返回 12:
DECLARE @reportId bigint = NULL,
@serviceId bigint = null;
SET @serviceId = 12;
SELECT CASE when @serviceId is null then rp.[value] else @serviceId end
from rep.reportparameters as rp
where rp.reportid = @reportId;
SELECT @serviceId
Why in PostgreSql case not working?为什么在 PostgreSql 情况下不起作用?
As documented in the manual , if no row is returned, then the INTO assignment will set the variable to NULL. 如手册中所述,如果未返回任何行,则 INTO 赋值会将变量设置为 NULL。 The CASE expression is never evaluated if no row is selected, so it can't change a NULL value into something different.
如果未选择任何行,则永远不会评估 CASE 表达式,因此它无法将 NULL 值更改为不同的值。
You can use coalesce()
with a direct assignment instead:您可以将
coalesce()
与直接赋值一起使用:
do $$
declare
_reportId bigint := null;
_serviceId bigint := null;
begin
_reportId := null;
_serviceid := 12;
_serviceid := coalesce((select rp.value::bigint
from rep.reportparameters as rp
where rp.reportid = _reportId), _serviceid);
RAISE NOTICE '%', _serviceId;
end;
$$;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.