【问题标题】:SQL - select data based on one specific input value or all if no input valueSQL - 根据一个特定的输入值选择数据,如果没有输入值则全部选择
【发布时间】:2015-12-15 21:31:29
【问题描述】:

我正在尝试使用作为客户代码的输入变量检索数据。如果用户输入客户代码,查询将检索该客户数据,但如果用户将客户代码留空,我想检索所有客户数据。下面是我可以根据“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$

【问题讨论】:

  • 这是什么数据库?
  • @Ruslan:看起来像 SQL Server
  • 那么 customer_ID 可以设置为“Blank”/空而不是 NULL 吗?或者 customer.id 中是否有非显示字符?
  • @xQbert:customer.id 的输入字段中似乎没有任何非显示字符。表格中的 customer_id 字段不能为空。
  • 那么$3_customer$ 上是否传入了空集''?我期待空

标签: sql


【解决方案1】:

另一种方法是:

open_item.customer_id = coalesce($3_customer$, open_item.customer_ID)

假设 $3_customer$ 为 NULL

所以 $3_customer$ 不能为空,所以使用 case

open_item.customer_id = case when $3_customer$ = '' 
                             then open_item.customer_ID else $3_customer$

coalesce 采用系列中的第一个非空值,本质上,当客户参数为空时,这将始终返回 TRUE。它这样做是因为它比较相同的值,因此总是相等;否则这将过滤提供的特定 $3_customer$

【讨论】:

  • 除非 customer_id 由于某种原因可以为 null 并且相等性测试失败。不过似乎不适用于这种情况。
  • 同意。如果 NULL 对 customer_Id 具有特殊意义,那么这不是一个合适的解决方案。
  • 这不起作用。我能够让所有客户列出的唯一方法是完全消除 WHERE 语句中对 customer_id 的任何引用,然后选择所有客户。
【解决方案2】:

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

and open_item.customer_id = $3_customer$

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

and ($3_customer$ IS NULL OR open_item.customer_id = $3_customer$) 

【讨论】:

  • 逻辑上A and not B or B 等价于A or B。但是优化器可能会使用额外的信息和短路。
  • @shawnt00 对!感谢您的关注。调整。
  • 这不起作用。我能够让所有客户列出的唯一方法是完全消除 WHERE 语句中对 customer_id 的任何引用,然后选择所有客户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 2011-05-20
  • 1970-01-01
相关资源
最近更新 更多