Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

Oracle IF Exists THEN, ELSE

I have the below SQL and giving me expression errors.

I want to check if the record exists, If Exists, then I want to execute one sql and get column values, If not I want to execute another sql and get columns values.

How can I do this oracle ?

DECLARE 
  VALIDEXISTS NUMBER;
BEGIN
  SELECT * 
    FROM table1 
   WHERE column1 IN ('Yes')
     AND columns2 IN (
                       SELECT COUNT(column1) AS VALIDEXISTS 
                         FROM table1 
                        WHERE column1 IN ('Yes') 
                          AND column2 NOT LIKE '%Yes%'
                           IF VALIDEXISTS = 0 THEN
                             SELECT column2 
                               FROM table1 
                              WHERE column1 IN ('Yes') 
                                AND column2 NOT LIKE '%Yes%'


                           ELSE 
                             SELECT column2 
                               FROM table1 
                               WHERE column1 IN ('Yes') 
                                 AND column2 NOT LIKE '%No%'    END IF; )
END
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calculate the condition first, then apply it to the final SELECT using CASE. Something like this:

with temp (validexists) as
  (select count(column1)
   from table1
   where column1 in ('Yes') 
      and column2 not like '%Yes%'
  )
  select *
    into l_row
    from table1
    where column1 in ('Yes')
      and column2 in (select column2
                      from table1 cross join temp
                      where column1 in ('Yes')
                        and column2 not like case when validexists = 0 then '%Yes%'
                                                  else                      '%No%'
                                             end
                     );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...