2017-04-20 66 views
0

我在處理plpgsql和RECORD類型時遇到了問題。Postgresql - 測試記錄類型(對於字段或null)

有誰知道一種方法來簡單地測試返回的記錄類型,以知道它是否設置?

基本模式:

甲函數返回一個記錄,並在那裏它可以是未固化的(即,選擇到沒有記錄返回)或它被設置爲一個單個記錄。

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; $$ 
+0

哪個Postgres版本您使用? – McNets

回答

0

對於RECORD,Ah ..是null操作符是(所有字段爲空),而不是null(所有字段都不爲空)。由於我有一些字段爲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;