oracle中的条件场景

时间:2015-04-16 05:02:21

标签: sql oracle where clause

我有条件

的要求

如果我的id在1中,那么它应该检查id 4,5,6,7或者它应该检查id中的值 这个id我将作为参数传递给查询

select * from table_a  where id 

帮助我

2 个答案:

答案 0 :(得分:2)

您可以使用以下

select * from individual ip 
 where ( 
    ( :p_prs_nat  = 219 and ip.prs_nationality_id in (231,259,343) ) 
     or (:p_prs_nat <> 219 and :p_prs_nat=ip.prs_nationality_id
   ))

答案 1 :(得分:0)

  

其中ip.prs_nationality_id =大小时:p_prs_nat在(219)然后它shud check(231,259,343)否则:p_prs_nat结束如何实现这个功能

CASE 表达式的 THEN 子句中返回结果时,无法直接使用 IN 。但是,您可以先使用 AND 运算符检查条件本身,并在匹配时返回 TRUE

例如,

SQL> WITH DATA AS
  2    (
  3    SELECT 1 ID, 'X' STR FROM DUAL UNION ALL
  4    SELECT 2 ID, 'A' STR FROM DUAL UNION ALL
  5    SELECT 3 ID ,'P' STR FROM DUAL UNION ALL
  6    SELECT 4 ID ,'Q' STR FROM DUAL
  7    )
  8  SELECT *
  9  FROM DATA
 10  WHERE (
 11    CASE
 12      WHEN ID  = 1
 13      AND str IN ('A','Y','Z')
 14      THEN 1
 15      WHEN ID <> 1
 16      THEN 1
 17    END ) =1
 18  /

        ID S
---------- -
         2 A
         3 P
         4 Q

SQL>

所以,你没有得到ID = 1的行,因为它与条件 AND str IN ('A','Y','Z') 不匹配。

如果它匹配,它也将返回那些匹配的行:

SQL> WITH DATA AS
  2    (
  3    SELECT 1 ID, 'X' STR FROM DUAL UNION ALL
  4    SELECT 2 ID, 'A' STR FROM DUAL UNION ALL
  5    SELECT 3 ID ,'P' STR FROM DUAL UNION ALL
  6    SELECT 4 ID ,'Q' STR FROM DUAL
  7    )
  8  SELECT *
  9  FROM DATA
 10  WHERE (
 11    CASE
 12      WHEN ID  = 1
 13      AND str IN ('X','Y','Z')
 14      THEN 1
 15      WHEN ID <> 1
 16      THEN 1
 17    END ) =1
 18  /

        ID S
---------- -
         1 X
         2 A
         3 P
         4 Q

SQL>