【问题标题】:Postgresql - testing RECORD types (for fields or null)Postgresql - 测试记录类型(用于字段或空)
【发布时间】:2017-09-17 10:53:10
【问题描述】:

我在处理 plpgsql 和 RECORD 类型时遇到问题。

有谁知道一种方法可以简单地测试返回的 RECORD 类型以了解它是否已设置?

基本模式:

一个函数返回一个 RECORD 并且它可能未设置(即选择返回没有记录)或者它被设置为单个记录。

create or replace function blah()
returns RECORD as $$
declare
  rec RECORD;
begin
   rec := row(null); --Do not want to hear about it not being assigned
   select *, status_field into rec ... ;
   if found then
       raise notice '%', rec.status_field is not null   --prints 't'
   end if

   if not found then
       raise notice '%', rec.status_field is not null   --Throws Error (I just want it to say 'f'
   end if; 
end; $$

create or replace function callblah()
returns text as $$
declare
  rtText text;
  blahRec RECORD;
begin
 blahRed := blah(...);

 -- what test can I do to determine if record is set or not.
 -- Try: if blah is not null then -- nope always returns false for is null and is not null
 -- Try: if blah.status is not null then -- nope throws error on field not existing
 -- What test condition do I need to add here to simply test if record is either (NOT FOUND) or (FOUND where field will exist).
 ...
 end if
end; $$

【问题讨论】:

  • 您使用的是哪个 Postgres 版本?

标签: postgresql plpgsql record


【解决方案1】:

Ah.. is null 运算符在 RECORD 上是(所有字段都为空),而不是空(所有字段都不为空)。因为我有一些字段 null 我需要做

if blah is null then
   -- No record found
else
   if blah.status is not null then
   -- Record found with field I want
   end if;
end if;

【讨论】:

  • 哇 - 这是出乎意料的行为,但它似乎确实以这种方式工作。你知道它记录在哪里吗?我看过这里:postgresql.org/docs/11/rowtypes.html,但仍然不清楚。
猜你喜欢
  • 1970-01-01
  • 2018-11-11
  • 2018-12-10
  • 2021-09-12
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 2023-03-27
  • 2017-08-02
相关资源
最近更新 更多