我想使用DB2实现这种类型的逻辑:
Create Procedure sp_MyProcedure (
IN Var1 Decimal(6, 0),
IN Var2 Decimal(6, 0)
) Language SQL
Dynamic Result Sets 1
Begin
If Exists(Select * from MyTable where CustomerNbr = Var1) Then
return (Select * from MyTable where CustomerNbr = Var1)
Else If Exists(Select * from MyTable where CustomerNbr = Var2) Then
return (Select * from MyTable where CustomerNbr = Var2)
Else
return (Select * from MyTable where CustomerNbr = 0)
End If
End
但无法弄清楚实现此类逻辑的语法。另外,我每次运行两次查询;一次检查它是否返回值,如果确实返回值,则一次创建返回的数据集。所以,我知道必须有更好的方法。我一直在查看“With”语句来创建临时表,但到目前为止,它基本上存在效率低下和语法限制相同的问题。
(我为代码的格式化道歉。我似乎无法让它在这个文本编辑器中正常工作) 有人可以建议最好的方法来实现这一目标吗? 提前谢谢您的建议。
答案 0 :(得分:2)
这是一个丑陋的select语句:
With allrecords as
(
Select 1 as qnum,*
from MyTable
where CustomerNbr = Var1
union all
Select 2 as qnum, *
from MyTable
where CustomerNbr = Var2
union all
Select 3 as qnum, *
from MyTable
where CustomerNbr = 0
)
select *
from allrecords
where qnum = (select min(qnum) from allrecords)
注意,如果你不想在结果中返回qnum,那么你必须为不包含qnum的最终select语句提供一个选择列表。
答案 1 :(得分:1)
我能想到的最好是:
SELECT * FROM MyTable
WHERE custNo = Var1
OR (custNo != Var1
AND custNo = Var2)
OR (custNo != Var1
AND custNo != Var2
AND custNo = 0);
答案 2 :(得分:0)
如果有人工作,你想要排除其他人。怎么样?
with A as
(select *
from mytable
where customer = var1
), Ax as
(select count(*) as tally
from a
), B as
(select *
from mytable, Ax
where Ax.tally = 0
and customer = var2
), Bx as
(select count(*) as tally
from B
), C as
(select *
from mytable, Ax, Bx
where Ax.tally=0
and Bx.tally=0
and Customer=0
)
select * from A
UNION
select * from B
UNION
select * from C