Postgresql

帶有可選參數的數據庫函式 SELECT

  • February 10, 2021

我需要在 postgres 中執行 SELECT,僅當某個參數值不為空時才過濾記錄。如果參數為空,則忽略該參數。我正在試驗一個功能…

create or replace function my_func(argument INT)
returns table
       (
           field1   VARCHAR(50),
           field2 VARCHAR(2),
           field3 BIGINT
       )
language plpgsql
AS
$$
begin
select d.field1, d.field2, COUNT(*) as record_count
            from my_table d
            group by d.field1, d.field2;

if argument IS NOT NULL
   -- TODO: How to filter the first recordset here?
end;
$$

請問如何在函式中執行第二個可選的 SELECT ?或者也許有一種巧妙的方法來做一個選項 where 子句?

select d.field1, d.field2, COUNT(*) as record_count

WHERE d.fieldX = argument OR argument IS NULL

from my_table d
group by d.field1, d.field2;

請注意,這可能並不總是產生有效的訪問計劃。如果您遇到性能問題,最好有條件地執行兩個查詢變體之一,例如

IF argument IS NULL THEN
  SELECT ... -- without conditions
ELSE 
  SELECT ... WHERE fieldX = argument
END IF

引用自:https://dba.stackexchange.com/questions/285158