简体   繁体   English

如何在where子句中使用Oracle的解码功能

[英]How to use Oracle's decode function in where clause

I have a query with few filter criteria, one of them is get to the query as integer parameter. 我有一个很少有过滤条件的查询,其中一个是作为整数参数进入查询的。 I want to use this filter only if this integer is > 0 I can't use NVL as it will never be null. 我只想在此整数> 0时使用此过滤器,因为它永远不会为null,所以我不能使用NVL。 How can I use DECODE in such case? 在这种情况下如何使用DECODE

SELECT (columns list)
        FROM 
        AGREEMENT A
        WHERE 
        A.ACCOUNT = 545 
        AND A.GRP_ID = NVL(?,A.GRP_ID)

The parameter ? 参数? I get is an Integer 我得到的是整数

You can use a case: 您可以使用一个案例:

SELECT (columns list)
    FROM 
    AGREEMENT A
    WHERE 
    A.ACCOUNT = 545 
    AND A.GRP_ID = CASE ? WHEN 0 THEN A.GRP_ID ELSE ? END

And Decode works in a similar fashion, although I think it's less readable. 尽管我认为解码的可读性较差,但解码的工作方式与此类似。

SELECT (columns list)
    FROM 
    AGREEMENT A
    WHERE 
    A.ACCOUNT = 545 
    AND A.GRP_ID = DECODE(?, 0, A.GRP_ID, ?)

But given the use case, making the parameter NULL would be a little better. 但是给定用例,将参数设置为NULL会更好一些。 After all, 0 is a value which you want to treat as a different value, while NULL semantically makes more sense for specifying 'no filter'. 毕竟,0是您要视为其他值的值,而NULL在语义上对于指定“无过滤器”更有意义。

Don't use decode() . 不要使用decode() It really is very old-fashioned. 它确实是非常老式的。 You can use case or just put the right logic as in: 您可以使用case或仅输入正确的逻辑,如下所示:

where a.account = 545 and
      (? = 0 or a.grp_id = ?)

Of course, this requires using the parameter twice. 当然,这需要两次使用参数。 However, that would also be necessary with decode() . 但是,这对于decode()也是必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM