我在purchase_order_status
表格中有一个名为purchases
的列,其中包含Open
和Closed
作为值。
SELECT *
FROM purchases
WHERE purchase_order_status = :status
如果用户将All
作为绑定参数传递,如何使用case语句获取具有Open
和Closed
状态的所有行,如下所示?
in ('Open','Closed')
是否可以在case语句中使用bind变量,例如
case when :status = 'All' then 'Open','Closed'
答案 0 :(得分:3)
您可以使用case
,但使用普通逻辑运算符更简单,更清晰:
SELECT *
FROM purchases
WHERE ((:status = 'All' AND purchase_order_status IN ('Open','Closed'))
OR purchase_order_status = :status)
使用一些简单的样本数据和一个SQL * Plus绑定变量:
create table purchases (purchase_order_status varchar2(10));
insert into purchases values ('Open');
insert into purchases values ('Closed');
insert into purchases values ('Pending');
var status varchar2(10);
传递'开放':
exec :status := 'Open';
anonymous block completed
SELECT *
FROM purchases
WHERE ((:status = 'All' AND purchase_order_status IN ('Open','Closed'))
OR purchase_order_status = :status);
PURCHASE_ORDER_STATUS
---------------------
Open
传递'All:
exec :status := 'All';
anonymous block completed
SELECT *
FROM purchases
WHERE ((:status = 'All' AND purchase_order_status IN ('Open','Closed'))
OR purchase_order_status = :status);
PURCHASE_ORDER_STATUS
---------------------
Open
Closed
如果您可以保证该列只能 保留这两个值,那么您可以将其进一步简化为:
SELECT *
FROM purchases
WHERE :status = 'All' OR purchase_order_status = :status;
答案 1 :(得分:1)
亚历克斯的回答是更好的IMO,但这里有另一种选择。
declare @test as varchar(10)
set @test = 'ALL'
if(@test='ALL') begin
select * from purchases where purchase_order_status in('Open','Closed')
end
if(@test='OPEN') begin
select * from purchases where purchase_order_status in('Open')
end
就个人而言,我会在生成选择查询的代码中做这种事情(如果有这样的代码)