2016-07-31 56 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 
     . . .