如何将case语句放在oracle 11g r2中的存储过程中的where子句中

时间:2014-07-25 10:53:42

标签: sql oracle plsql

我陷入了一个问题..我从网上搜索过它并找到了这样的解决方案..

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;

下面 PARM_ML,PARM_ANALYSIS_TYP,PARM_TYP_ST 是作为输入参数传递的参数。 和 LOC_ROW_ID是用于获取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

我是对的,还是应该寻求另一种解决方案。请建议。

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

1 个答案:

答案 0 :(得分:0)

我认为这是你正在寻找的逻辑:

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

这使PARM_PLAN_CDE成为可选参数。 NULL时,它不会过滤数据。

通常,where子句在没有where子句的情况下更具可读性。