Postgres 未分配记录,有没有办法测试空值?

Postgres unassigned record, is there a way to test for null?

有什么方法可以测试未分配的记录是否为空? (抱歉,sqlfiddle 不喜欢我的 DO 块。)谢谢。

DO
$$
DECLARE
r record;
BEGIN

r := null;

if r is null    -- ERROR:  record "r" is not assigned yet
then
end if;

END
$$;

如果您使用异常处理程序包装测试,您可以使用 "not initialized" 错误来为您进行检查。

DO $$
DECLARE
r record;
BEGIN

r := null;

  BEGIN
    IF r IS NOT NULL THEN
        raise notice 'R IS INITIALIZED';
    END IF;
  EXCEPTION
    WHEN OTHERS THEN
        raise notice 'R IS NOT INITIALIZED';
  END;

END
$$;

错误可以通过写来避免:

   select null into r;

或者:

   r:=row(null);

这样 r 使用元组结构进行初始化。

不过,请注意,记录变量在涉及 NULL 的其他方面并不直观,而且通常很难在其基本用例(游标式迭代)之外使用。

select *
from t
where id = p_id
into r;

if found then
...
else
...
end if;

https://www.solvingsoftware.dev/testing-for-an-empty-record-variable-in-postgresql/