[英]SQL Column Parameter Bind Variable with either or logic
I apologize if the title is misleading. 如果标题误导我,我深表歉意。
I'm trying to avoid using two different queries. 我试图避免使用两个不同的查询。 With that in mind,
考虑到这一点,
I have the following sample query 我有以下示例查询
SELECT COUNT (*) COUNT,
SUM (AMT) AS DED_AMT,
SUM (SURCOST),
SUM (DEALSUM),
NVL (TO_CHAR (SUM (RETAIL)), 'N/A') AS RETAIL,
MNFCID
FROM (SELECT B.ID, B.CD, A.*
FROM OUTPUTS_A A JOIN OUTPUTS_B B ON A.ID = B.ID
WHERE B.ID = :ID AND B.CD = UPPER (:CD))
GROUP BY ID;
that returns a result you can see in the first screenshot. 返回的结果可以在第一个屏幕截图中看到。
Notice, I'm passing two bind variables in the query, :ID, :CD. 注意,我在查询中传递了两个绑定变量:ID,:CD。 They have to go together and that's why I'm using AND operator there.
他们必须走在一起,这就是为什么我在那里使用AND运算符的原因。
Sometimes, I have MFCID only and not :ID and :CD. 有时,我只有MFCID,而没有:ID和:CD。
This is the logic I'm thinking about. 这就是我正在考虑的逻辑。
I would like to modify the query such a way that I should be able to pass MFCID as a bind variable. 我想以某种方式修改查询,以便能够将MFCID作为绑定变量进行传递。 Let's say :mfcid is the variable I'm passing.
假设:mfcid是我要传递的变量。
If I have the values for :ID and :CD handy, I will pass those values and pass nothing for :mfcid. 如果方便使用:ID和:CD的值,则将传递这些值,而对于:mfcid不传递任何值。 (Nothing in a sense that I won't pass anything. This field CAN'T be null)
(从某种意义上说,我什么都不会通过。此字段不能为空)
If I only have the value for :mfcid handy, I will pass that value and pass nothing for :ID and :CD. 如果仅提供:mfcid的值,则将传递该值,而对:ID和:CD不传递任何值。 (Nothing in a sense that I won't pass anything. This field CAN'T be null)
(从某种意义上说,我什么都不会通过。此字段不能为空)
Either way it should return me the same result. 无论哪种方式,它都应该返回相同的结果。
I have tried putting it this way: AND B.MNFCID = NVL(:MNFCID, B.MNFCID)
but it takes forever because it's always true if don't pass anything. 我试过这样写:
AND B.MNFCID = NVL(:MNFCID, B.MNFCID)
但它要花很多时间,因为如果不传递任何东西,它总是正确的。
Does this do what you want? 这是您想要的吗?
SELECT COUNT(*) COUNT, SUM(AMT) AS DED_AMT, SUM(SURCOST),
SUM(DEALSUM), NVL(TO_CHAR(SUM(RETAIL)), 'N/A') AS RETAIL,
MNFCID
FROM OUTPUTS_A A JOIN
OUTPUTS_B B
ON A.ID = B.ID
WHERE (B.ID = :ID OR :ID IS NULL) AND
(B.CD = UPPER(:CD) OR :CD IS NULL)
GROUP BY B.ID;
If this doesn't work -- and it might not -- you may want to use dynamic SQL so the appropriate indexes can more readily be used. 如果这行不通(也可能行不通),则可能要使用动态SQL,以便可以更轻松地使用适当的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.