首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL -基于一个特定输入值选择数据,如果没有输入值,则选择所有数据

SQL -基于一个特定输入值选择数据,如果没有输入值,则选择所有数据
EN

Stack Overflow用户
提问于 2015-12-16 05:31:29
回答 2查看 64关注 0票数 0

我正在尝试使用作为客户代码的输入变量来检索数据。如果用户输入客户代码,则查询将检索该客户数据,但如果用户将客户代码留空,则我希望检索所有客户数据。下面是代码,我可以根据在'3_customer‘中输入的客户代码来检索数据,但我不知道如何执行这种IF-THEN-ELSE类型的查询。如果输入变量留空,我需要获取所有客户的数据。

谢谢,唐

代码语言:javascript
复制
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$
EN

回答 2

Stack Overflow用户

发布于 2015-12-16 05:38:34

另一种方法是:

代码语言:javascript
复制
open_item.customer_id = coalesce($3_customer$, open_item.customer_ID)

假设$3_customer$将为空

因此$3_customer$不能为null,因此请使用大小写

代码语言:javascript
复制
open_item.customer_id = case when $3_customer$ = '' 
                             then open_item.customer_ID else $3_customer$

coalesce在本质上接受序列中的第一个非空值,当客户参数为空时,它将始终返回TRUE。它之所以这样做,是因为它比较相同的值,因此总是相等;否则,它将根据提供的特定$3_customer$进行过滤

票数 2
EN

Stack Overflow用户

发布于 2015-12-16 05:35:44

您需要稍微更改客户条件的WHERE子句:

代码语言:javascript
复制
and open_item.customer_id = $3_customer$

如下所示:(下面的代码假设将$3_customer$插入到查询字符串中,如果为空,则设置为NULL )

代码语言:javascript
复制
and ($3_customer$ IS NULL OR open_item.customer_id = $3_customer$) 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34299782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档