2017-02-27 36 views
0

我想从同一个SP中选择所有客户或一个客户。现在我们正在mantaining两个SP来获得这些信息:我的SQL:如果在where语句中添加条件?

即要获得所有客户:

select id, name from customers 

,并获得一个客户:

select id, name from customers 
where id=id_from_input 

使它们成为通用,我想的将id_from_input定为空以获得所有客户。我尝试了几种方法在sql中创建一个条件where语句,该语句可用于此计划,但没有任何工作。例如:

select id, name from customers 
where if(id_from_input <> null) id=id_from_input; end if 

给我语法错误。

如何在id_from_input为空时返回所有行的where子句,否则为匹配行?

+0

'CASE WHEN'是查询了'IF'语法。 – Hexxed

回答

1

表达x <> null是不正确的;您只能使用is nullis not null来测试null。纠正你试图给:

select id, name from customers 
where id_from_input is null or id = id_from_input 

或者一些更简洁(恕我直言优雅):

select id, name from customers 
where id = coalesce(id_from_input, id) 
+0

这工作正常。正确答案。 – maverick

1

使用CASE语句来实现你的结果:

SELECT id, name FROM customers WHERE id = CASE WHEN ISNULL(id_from_input,'') 
<> '' THEN id_from_input ELSE id END 
0

尝试使用or

select id, name 
from customers 
where id_from_input is null or id = id_from_input 

如果id_from_input为null,则or条款将不被计算。

0

尝试此查询

select id, name from customers where CASE WHEN id_from_input<>null THEN id=id_from_input ELSE id END