简体   繁体   中英

How do I create a conditional SQL query

I am trying to create an Oracle Sql query using IF/Else statements

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;

However I receive an "Unknown Command" error when I run it. No more error information

This may provide what you are looking for:

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
        )
      )
    )

Another way

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
      )
    )

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