Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

sql - How to use Alias in Where clause?

I have this procedure:

 PROCEDURE P_LOAD_EXPIRED_ACCOUNT
  (
  pDayDiff IN NUMBER,
  ExpiredCur OUT MEGAGREEN_CUR
  )
  IS
  BEGIN
  OPEN ExpiredCur FOR
  SELECT 
  ACCOUNT_NAME, SERVICE_TYPE, 
      CASE 
      WHEN SERVICE_TYPE = 1 THEN ADD_MONTHS(ACTIVATED_DATE,3)
      WHEN SERVICE_TYPE = 2 THEN ADD_MONTHS(ACTIVATED_DATE,6)
      WHEN SERVICE_TYPE = 3 THEN ADD_MONTHS(ACTIVATED_DATE,12)        
       END 
       AS EXPIRED_DATE
  FROM SUBSCRIBERS
  WHERE (EXPIRED_DATE - CURRENT_DATE) < pDayDiff;
  END;

but SQL Developer generate this error:

Error(20,10): PL/SQL: ORA-00904: "EXPIRED_DATE": invalid identifier

I believe that PLSQL allows me to use Alias in Where clause, but is there something I forgot?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't reference the column alias in the WHERE clause - your options are:

  • replicate the CASE statement in the WHERE clause
  • use a subquery:

    PROCEDURE P_LOAD_EXPIRED_ACCOUNT(pDayDiff NUMBER,
                                     ExpiredCur OUT MEGAGREEN_CUR)
    IS
    BEGIN
    
    
       OPEN ExpiredCur FOR
       SELECT x.account_name,
              x.service_type, 
              x.expired_date
         FROM (SELECT s.account_name,
                      s.service_type, 
                      CASE 
                         WHEN s.service_type = 1 THEN ADD_MONTHS(ACTIVATED_DATE,3)
                         WHEN s.service_type = 2 THEN ADD_MONTHS(ACTIVATED_DATE,6)
                         WHEN s.service_type = 3 THEN ADD_MONTHS(ACTIVATED_DATE,12)        
                      END AS EXPIRED_DATE
                 FROM SUBSCRIBERS s) x
        WHERE x.expired_date - CURRENT_DATE < pDayDiff;
    
    
    END;
    

    Oracle 9i+

    WITH summary AS (
      SELECT s.account_name,
             s.service_type, 
             CASE 
                WHEN s.service_type = 1 THEN ADD_MONTHS(ACTIVATED_DATE,3)
                WHEN s.service_type = 2 THEN ADD_MONTHS(ACTIVATED_DATE,6)
                WHEN s.service_type = 3 THEN ADD_MONTHS(ACTIVATED_DATE,12)        
             END AS EXPIRED_DATE
        FROM SUBSCRIBERS s)
       SELECT x.account_name,
              x.service_type, 
              x.expired_date
         FROM summary x
        WHERE x.expired_date - CURRENT_DATE < pDayDiff;
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...