简体   繁体   中英

how to put case statement in where clause in Stored procedure in oracle 11g r2

I am stuck in a problem.. I have searched it from net and found solution like this..

SELECT B.ROW_ID INTO LOC_ROW_ID 
FROM
 (SELECT ROWNUM AS ROW_ID, 
                   A.YEAR, 
                   A.PERIOD 
  FROM
   (SELECT DISTINCT TP.YEAR, 
                    TP.MONTH
     FROM TB_PLAN TP
    WHERE
        ML_TYP=PARM_ML
        AND ANALYSIS_TYP=PARM_ANALYSIS_TYP
   **   AND CASE 
               WHEN PARM_TYP_ST IS NULL THEN PLAN_CDE 
               END=PARM_PLAN_CDE 
        AND CASE
                WHEN PARM_TYP_ST IN NOT NULL THEN PLAN_CDE
                END=PARM_PLAN_CDE     **
        ORDER BY YEAR DESC, MONTH DESC
     )A 
       )B
       WHERE
            B.YEAR=2013
            AND PERIOD=3;

Here PARM_ML, PARM_ANALYSIS_TYP, PARM_TYP_ST are parameter passed as input parameter. And LOC_ROW_ID is local parameter to fatch value of ROW_ID

 I dont know whether this is approach for my problem or not.  But not getting any            .    result from this query

what i want to do is..
using same query for two cases
    case1: when 
     ML_TYP=PARM_ML
     AND ANALYSIS_TYP=PARM_ANALYSIS_TYP
     AND PLAN_CDE =PARM_PLAN_CDE 

    case2: when
      ML_TYP=PARM_ML
      AND ANALYSIS_TYP=PARM_ANALYSIS_TYP

Am i going right or should go for another solution. Please suggest.

Basic query is

SELECT DISTINCT TP.YEAR, 
                    TP.MONTH
     FROM TB_PLAN TP
    WHERE
        ML_TYP=PARM_ML
        AND ANALYSIS_TYP=PARM_ANALYSIS_TYP
   **   AND CASE 
               WHEN PARM_TYP_ST IS NULL THEN PLAN_CDE 
               END=PARM_PLAN_CDE 
        AND CASE
                WHEN PARM_TYP_ST IN NOT NULL THEN PLAN_CDE
                END=PARM_PLAN_CDE     **
        ORDER BY YEAR DESC, MONTH DESC

I think this is the logic you are looking for:

WHERE ML_TYP = PARM_ML AND
      ANALYSIS_TYP = PARM_ANALYSIS_TYP AND
      (PARM_TYP_ST IS NOT NULL OR PLAN_CDE = PARM_PLAN_CDE)

This makes PARM_PLAN_CDE an optional parameter. When NULL , it will not filter the data.

In general, where clauses are more readable without where clauses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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