2016-07-31 77 views
1

嘗試在Postgresql中用4個返回表(多行)的參數創建函數。 參數:in_customer_id, in_start_date, in_end_date, in_risk_flag返回多個行作爲逗號分隔值,當語句爲

我正在使用該功能的SQL查詢:我得到

select * from customer as k 
where k.customer_id IN (case when $1 = 0 then (select distinct(customer_id) from customer) 
          when $1 != 0 then $1 
          end) 
and k.start_date >= $2 
and k.end_date <= $3 
and k.risk_flag IN (case when $4 = 0 then (select distinct(risk_flag) from customer) 
         when $4 != 0 then $4 
         end) 

錯誤是錯誤[21000]:more than one row returned by subquery used as an expression

有沒有辦法從case語句返回(1,2,3,4,5,6)(逗號分隔值)而不是多行的列?

回答

1

第一個:distinct不是函數。寫作distinct (customer_id)是沒有意義的。而在用於IN條件的子選擇中,distinct無論如何都是無用的。


看來你想選擇一個特定的客戶,如果你傳遞一個參數,否則你想選擇所有的。據我所知,你不需要一個子選擇。類似的東西,應該這樣做:

where k.customer_id = case 
         when $1 <> 0 then $1 
         else k.customer_id 
         end 

當第一個參數爲0傳遞(雖然你應該更好地使用空值對於這一點,而是一個「神奇」的價值像零,那麼它實際上變成了條件where customer_id = customer_id

這裏假定customer_id被定義爲NOT NULL否則這將不起作用。

您可以對risk_id應用相同的模式(同樣:只有當risk_id不能包含NULL值時它纔會起作用)。

0

該邏輯通常簡化爲避免casewhere子句中:

where ($1 = 0 or $1 = k.customer_id) and 
     . . . 
相關問題