在oracle中使用子查询的TRUNC(date)

时间:2016-12-15 11:20:17

标签: oracle plsql oracle11g

我有一个IF条件,它检查子查询中的日期,如下所示

IF (TRUNC(lv_d_itr) IN
(SELECT next_day(TRUNC(to_date('01-01-17','dd-mm-yy'),'YYYY') + 14*(level-1), 'WED' )+7
 FROM dual
 CONNECT BY level <= 26)) THEN

为什么我收到以下错误?用法不对?

PLS-00405: subquery not allowed in this context

什么是替代解决方案?

2 个答案:

答案 0 :(得分:3)

您不能在pl / sql IF语句中使用子查询:

BEGIN
  IF 'X' IN ( SELECT DUMMY FROM DUAL ) THEN
    DBMS_OUTPUT.PUT_LINE( 'X' );
  END IF;
END;
/

PLS-00405: subquery not allowed in this context

会出错

您可以重构它以获得相同的效果:

DECLARE
  p_exists NUMBER;
BEGIN
  SELECT CASE WHEN 'X' IN ( SELECT DUMMY FROM DUAL )
              THEN 1
              ELSE 0
         END
  INTO   p_exists
  FROM   DUAL;

  IF p_exists = 1 THEN
    DBMS_OUTPUT.PUT_LINE( 'X' );
  END IF;
END;
/

答案 1 :(得分:1)

你可以用不同的方式编辑它,一个简单的方法可能是:

declare
  n number;
begin
    select count(1)
    into n
     from
        (       
         SELECT next_day(TRUNC(to_date('01-01-17','dd-mm-yy'),'YYYY') + 14*(level-1), 'MER' )+7 as x
         FROM dual
         CONNECT BY level <= 26
        )
     where x = TRUNC(lv_d_itr);
    if n > 0
      then ...
    end if;
    ...
end;