我正在尝试使用作为客户代码的输入变量来检索数据。如果用户输入客户代码,则查询将检索该客户数据,但如果用户将客户代码留空,则我希望检索所有客户数据。下面是代码,我可以根据在'3_customer‘中输入的客户代码来检索数据,但我不知道如何执行这种IF-THEN-ELSE类型的查询。如果输入变量留空,我需要获取所有客户的数据。
谢谢,唐
SELECT
open_item.order_id order_id,
convert(varchar(10),orders.ordered_date,101) order_date,
orders.revenue_code_id,
orders.operations_user,
open_item.customer_id cust_no,
customer.name cust_name,
convert(varchar(10),open_item.gl_date,101) adjust_date,
open_item.amount amount,
open_item.record_type type,
open_item.ar_reason_code_id,
ar_reason_code.descr reason
FROM
open_item
LEFT OUTER JOIN
customer ON customer.id = open_item.customer_id
LEFT OUTER JOIN
ar_reason_code ON open_item.ar_reason_code_id = ar_reason_code.id
LEFT OUTER JOIN
orders ON orders.id = open_item.order_id
WHERE
open_item.gl_date >= $1_sdate$ AND
open_item.gl_date <= $2_edate$ AND
open_item.source = 'C' AND
open_item.record_type = 'C' AND
open_item.customer_id = $3_customer$发布于 2015-12-16 05:38:34
另一种方法是:
open_item.customer_id = coalesce($3_customer$, open_item.customer_ID)假设$3_customer$将为空
因此$3_customer$不能为null,因此请使用大小写
open_item.customer_id = case when $3_customer$ = ''
then open_item.customer_ID else $3_customer$coalesce在本质上接受序列中的第一个非空值,当客户参数为空时,它将始终返回TRUE。它之所以这样做,是因为它比较相同的值,因此总是相等;否则,它将根据提供的特定$3_customer$进行过滤
发布于 2015-12-16 05:35:44
您需要稍微更改客户条件的WHERE子句:
and open_item.customer_id = $3_customer$如下所示:(下面的代码假设将$3_customer$插入到查询字符串中,如果为空,则设置为NULL )
and ($3_customer$ IS NULL OR open_item.customer_id = $3_customer$) https://stackoverflow.com/questions/34299782
复制相似问题