[英]Postgres Check for Empty JSONB Fields
我想能夠ignore
或阻止INSERT
的發生,如果有一個具有鍵的JSON對象但Postgres函數中沒有值,這是一個小的人為例子:
DROP TABLE IF EXISTS mytable;
create table mytable(
a text,
b text
);
CREATE OR REPLACE FUNCTION insert_to_table(
somedata JSONB
)
RETURNS VOID AS $$
BEGIN
insert into mytable (a, b) select a,b from jsonb_populate_recordset(null::mytable, $1::jsonb);
END;
$$ LANGUAGE plpgsql;
select insert_to_table('[{"a":1,"b":2},{"a":3,"b":4}, {"a":null, "b": null}, {"a": null, "b": "some data"}]');
這將插入4條記錄,第一行為1,2
,下一行為3,4
。 第三行是"", ""
,第四行是"", some data
。
在這種情況下,行1,2和4有效。 我想忽略3並阻止其插入。
我不希望有空白行,並且我的數據/表將比列出的數據大得多(表中大約有20個字段,JSON中有20個鍵/值對)。
我很可能需要遍歷數組,並選擇所有鍵均為null而不只是1或2的JSON
對象。
我怎樣才能做到這一點?
在Postgres中,您可以使用查詢中的表名(別名)來引用完整的行,並將其與NULL比較。 如果所有列均為空,則記錄被視為NULL。 因此,您可以執行以下操作:
create or replace function insert_to_table(somedata jsonb)
returns void as $$
begin
insert into mytable (a, b)
select a, b
from jsonb_populate_recordset(null::mytable, somedata) as t
where not (t is null);
end;
$$ language plpgsql;
請注意, where t is not null
where not (t is null)
不同where not (t is null)
有所不同。 無論列數或其數據類型如何,此方法均有效。
可視化邏輯。 下列:
select a,b,
not (t is null) as "not (t is null)",
t is null as "t is null",
t is not null as "t is not null"
from jsonb_populate_recordset(null::mytable,
'[{"a":1,"b":2},
{"a":3,"b":4},
{"a":null, "b": null},
{"a": null, "b": "some data"}]'::jsonb) as t(a,b)
收益:
a | b | not (t is null) | t is null | t is not null
--+-----------+-----------------+-----------+--------------
1 | 2 | true | false | true
3 | 4 | true | false | true
| | false | true | false
| some data | true | false | false
無關:
$1::jsonb
無效,因為您已經聲明了該類型的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.