如何创建条件SQL查询

时间:2015-07-18 04:06:19

标签: sql oracle syntax conditional

我正在尝试使用IF / Else语句创建Oracle Sql查询

IF EXISTS 
  ( 
         SELECT * 
         FROM   baninst1.an_employee_position 
         WHERE  baninst1.an_employee_position.person_uid = 593791 
         AND    baninst1.an_employee_position.position_end_date IS NULL) THEN 
  SELECT * 
  FROM   baninst1.an_employee_position 
  WHERE  baninst1.an_employee_position.person_uid = 593791 
  AND    ( 
                baninst1.an_employee_position.position_end_date IS NULL 
         OR     baninst1.an_employee_position.position_end_date > SYSDATE) 
  AND    baninst1.an_employee_position.effective_start_date <= SYSDATE;ELSE 
  SELECT * 
  FROM   ( 
                SELECT * 
                FROM   baninst1.an_employee_position 
                WHERE  baninst1.an_employee_position.person_uid = 593791 ) 
  WHERE  ROWNUM = 1;END IF;

然而,我收到一个&#34;未知命令&#34;我运行它时出错。没有更多的错误信息

1 个答案:

答案 0 :(得分:4)

这可能会提供您所需要的内容:

SELECT a.* 
 FROM employee_position a
where person_uid = 593791
and (
      (a.position_end_date is null)
      or
      (
        a.position_end_date =
        (select max(position_end_date)
         from employee_position b
          where b.person_uid = a.person_uid
          and b.position_end_date is not null
        )
      )
    )

另一种方式

SELECT a.* 
 FROM employee_position a
where person_uid = 593791
and (
      nvl(a.position_end_date, trunc(sysdate+100)) >= 
      (select max(position_end_date)
       from employee_position b
       where b.person_uid = a.person_uid
       and b.position_end_date is not null
      )
    )