简体   繁体   中英

Better ways to write SQL statement in DB2 which makes use of “EXISTS” keyword

I have written below SQL in an RPGLE program. Intent is to update the header file (TC400F) if no corresponding records exist in detail file (TC401F). Are there better ways of doing this? By better, I mean that would make the query run faster or would make it look more cleaner.

Exec SQL UPDATE  TC400F                     
            SET  T40STS = '05',             
                 T40OFL = '1'               
          WHERE  T40SID = :K#T41SID AND     
                 T40PID = :K#T41PID AND     
     NOT EXISTS  (SELECT * FROM TC401F WHERE
                 T41SID = :K#T41SID AND     
                 T41PID = :K#T41PID ); 

try this :

Exec SQL UPDATE  TC400F f1                     
         SET    (f1.T40STS, f1.T40OFL) = ('05', '1')             
         WHERE  f1.T40SID = :K#T41SID AND     
                f1.T40PID = :K#T41PID AND     
         NOT EXISTS  
         ( 
           SELECT * FROM TC401F f2 
           WHERE (f1.T41SID, f1.T41PID) = (f2.T41SID, f2.T41PID)
         );    

You have not done anything here that explicitly restricts performance. The optimizer is pretty smart these days. Most of the things that affect SQL performance are external to the statement. Best to write the statement to be semantically correct (as you have above), and let the optimizer do it's thing. Then if you see performance issues, then investigate them with then Explain tools in Run SQL Scripts . Most likely your performance issues will derive from incorrect indexes.

Exec SQL UPDATE  TC400F                     
            SET  T40STS = '05',             
                 T40OFL = '1'               
          WHERE  (t40sts <> '05' or t40ofl <> '1')
                 and T40SID = :K#T41SID 
                 AND T40PID = :K#T41PID
                 and      
     NOT EXISTS  (SELECT onefieldhere FROM TC401F WHERE
                 T41SID = :K#T41SID AND     
                 T41PID = :K#T41PID ); 

Add a little optimistic code don't update what is already set. Please don't make the as400 an orphan by ending a line with an operator that is the start of the next line. Optimistic updates are probably fastest when values are already set because it knows its already done. You could make it better by using the alias field names so someone in the future will know what a t40ofl is. Select only one field from the exists clause so sql won't have to pull in a whole row.

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