SQL - 如果不是这样,我可以做其他部分

时间:2018-04-18 10:40:23

标签: mysql sql database oracle

我可以在if上执行if if:P_Prestay为true执行此操作,否则执行此操作。这是我尝试但有语法错误,我不知道我该怎么做

AND R.RES_ESTRES = 'CM'
AND R.RES_SISCRE IN ('MPH','HPH')
**((AND BOOKINGENGINECODE = :P_BOOKINGENGINECODE
AND :P_PRESTAY like 'true')
(AND TRUNC(R.RES_FECINI) = TRUNC(SYSDATE)+2
and :P_POSTSTAY like 'true'
AND TRUNC(R.RES_FECFIN) = TRUNC(SYSDATE)-1))**

我的英语。

3 个答案:

答案 0 :(得分:0)

您可以创建PL块或过程参数。使用if条件检查参数值。 请查看以下链接:

https://docs.oracle.com/cloud/latest/db112/LNPLS/controlstatements.htm#LNPLS386  要么 using "if" and "else" Stored Procedures MySQL

答案 1 :(得分:0)

您可以在条件中使用案例陈述

with tab1 as (select 1 "ID", 1 "TAKECOL", 10 "C1", 20 "C2" from dual
union all select 2 "ID", 1 "TAKECOL", 10 "C1", 20 "C2" from dual
union all select 3 "ID", 2 "TAKECOL", 20 "C1", 10 "C2" from dual
union all select 4 "ID", 2 "TAKECOL", 20 "C1", 20 "C2" from dual)
select * 
from tab1
where case takecol 
        when 1 then c1 
        else c2 
      end = 10;

返回ID 1,2和3,但不返回4

有关案例的定义,请参阅oracle documentation

答案 2 :(得分:0)

您需要括号外的AND

AND R.RES_ESTRES = 'CM'
AND R.RES_SISCRE IN ('MPH','HPH')
AND (  (
           :P_PRESTAY = 'true'
       AND BOOKINGENGINECODE = :P_BOOKINGENGINECODE
       )
    OR (
           ( :P_PRESTAY <> 'true' OR :P_PRESTAY IS NULL ) -- This will only be true if
                                                          -- the previous condition is not
                                                          -- true.
       AND :P_POSTSTAY  = 'true'
       AND R.RES_FECINI >= TRUNC( SYSDATE ) + 2
       AND R.RES_FECINI <  TRUNC( SYSDATE ) + 3
       AND R.RES_FECFIN >= TRUNC( SYSDATE ) - 1
       AND R.RES_FECFIN <  TRUNC( SYSDATE )
       )
    )

此外,如果您使用TRUNC( datevalue ),则Oracle无法在列上使用索引,并且需要基于函数的索引,因此指定日期值的范围通常更有效,而不是比较截断日期。< / p>