Optimize this applescript?

Hi all,
I'm trying to build an applescript which is running everyday and all the time on my computer like 24h forever.
That's the reason why I would love to have it as simple, and as efficient as possible. Without having me to manually quit or restart it if anything happens.
It will essentially check for application to be active, if not depending on the folder it sees, it reopens those application.
If it does detect another folder it scans the media to see if a blank CD is insert, if so launches the main APP (APP0)
So, right now it is working properly, just asking you guys if you see a way to make it better, and more reliable. Thanks a lot!
repeat while 1 = 1
  delay 5
          repeat while application "APP0" is not running and application "APP1" is not running and application "APP2" is not running and application "APP3" is not running
  delay 2
                    tell application "Finder"
                              if exists folder "mypath:v" then
                                        if exists folder "mypath:v:1" then
                                                  try
                                                            tell application "APP1" to activate
                                                  end try
                                        else if exists folder "mypath:v:2" then
                                                  try
                                                            tell application "APP2" to activate
                                                  end try
                                        else if exists folder "mypath:v:3" then
                                                  try
                                                            tell application "APP3" to activate
                                                  end try
                                        end if
                              else if exists folder "mypath:m" then
                                        try
                                                  tell application "APP0" to activate
                                        end try
  -- CD INSERITO
                              else if exists folder "mypath:o" then
                                        set r to do shell script "/usr/bin/drutil status"
                                        delay 10
  -- SUPPORTI NON ADATTI
                                        if r contains "DVD-ROM" or r contains "DVD+R" or r contains "DVD-R" or r contains "CD+R" then
                                                  try
                                                            do shell script "drutil eject"
                                                  end try
  -- CD-R OK
                                        else if r contains "CD-R" then
                                                  if r contains "blank" then
                                                            tell application "APP0" to activate
                                                  else if r does not contain "blank" then
                                                            try
                                                                      do shell script "drutil eject"
                                                            end try
                                                  end if
                                        end if
                              end if
                    end tell
          end repeat
end repeat

This looks a bit like gibberish but what I would suggest is a function ZZZ that takes three parameters (A, B, C.COD), evaluates them using YYY and XXX and returns a trivalent result that you can use in the WHERE clause.
An even smarter solution might be to have the ZZZ return a user-defined nested table type of A, B that can be used in a TABLE() function in the FROM clause.
Cheers, APC

Similar Messages

  • This Applescript will correct links & programs for posting

    Since I have been posting to these forms, I have been annoyed by the conversions that are done to my posts. A word surrounded by asterisks gets bolded. When I decide to make a link to a post, I can never remember the exact format. When I posted AppleScript code, I found that it is squish to the left. The AppleScript I have posted here gets around these problems.
    Robert
    The first thing that you need to do is to make the text into an AppleScript program.
    start the AppleScript Editor
    /Applications/AppleScript/Script Editor.app
    copy the text to the Applescript editor.
    save the text to a file as an application and do not check any of the boxes below.
    !http://farm4.static.flickr.com/3544/3390737677_645a847e28.jpg?v=0!
    now, let's build a link to a post.
    get the link to a reply.
    Goto this Webpage:
    http://discussions.apple.com/post!reply.jspa?messageID=9003196
    Copy the Web page address from the top of your Web browser page. This is the standard highlight the address then do a command+c
    Now you should run my AppleScript program by going back to the Script Editor. Optional, click the words event log to see the debug information. Click on the run icon.
    !http://farm4.static.flickr.com/3423/3391549168_9ce8b6fcd9.jpg?v=0!
    The link has been modified. Paste the link onto your Web page. This is the standard command+v.
    For a more typical usage, placed the program on the dock or make an alias on the desktop.
    Robert
    Name: alter-clipboard
    Input: Clipboard
    Output: Clipboard
    This AppleScript program is designed to convert a forum-reply web address  to a link to a forum post, to convert special characters to their HTML symbols, and to convert programming language code to a  form that does not get mangled.
    1)   When you wish to reference another Apple discussion forum post, I found the process convoluted.  The Apple form software does not provide for the display of a form post link.  Instead, you must  construct the link from a reply post.  This AppleScript simplifies the process.
      When the clipboard contains a link to a forum reply page, do the conversion.
      Here is that way:
      a) Find the particular post you wish to reference.  
      b) Click on the reply icon.  
      c) Copy  the Web address to the clipboard  (command+c).  
      d) Run this AppleScript to convert the Web address.  
      e) Paste (command+v) the converted Web address into your post.
       For example, you:  
       • Want to reference a post on how to improve the performance of Tiger.  You find a post by Texas Mac Man with a list of possibilities.  
       • Click on the Reply option and highlight the Web address because you know the address contains a reference to this post.
       • Type command+c to copy the address to the clipboard.  The clipboard now contains:
         http://discussions.apple.com/post!reply.jspa?messageID=9124252
       •  Run this AppleScript to convert the Web address. The clipboard now contains:   
               http://discussions.apple.com/message.jspa?messageID=9124252#9124252
       • Type command+v to paste the address   into your new post.
    2)  Assume that the clipboard contains  special symbols or formated programming language code to convert.  
      The simpleFormatting property switch in the code selects teletype text ( tt ) when true and selets preformated text ( pre ) when false.      
      This AppleScript will converted special symbols used in these forums to a form not used by the forum software in order to preserve the original characters.
      For the symbols, see:
      See "Other formating tags are available as shown below" in
      http://discussions.apple.com/help.jspa#format
      An alternative to using these symbols is document in this post:
      http://discussions.apple.com/thread.jspa?messageID=607563
      Also, this AppleScript preserves indentation used in programs or Terminal output.
      a) Copy  the text to the clipboard .  
      b) Run this AppleScript to convert the text
      c) Paste the converted text into your post.
      For example,  the asterisks will be preserved:
         mac $ ls *oup*
         Youpi Key Editor.plist  Youpi Key.app alias  
      For example,  the indentation will be preserved:
         on adding folder items to this_folder after receiving dropped_items
            repeat with dropped_item_ref in dropped_items
               display dialog "dropped files is " & dropped_item_ref
            end repeat
         end adding folder items to
      Author: rccharles
      Copyright 2009 rccharles
      GNU General Public License
       This program is free software: you can redistribute it and/or modify
       it under the terms of the GNU General Public License as published by
       the Free Software Foundation,  version 3
       This program is distributed in the hope that it will be useful,
       but WITHOUT ANY WARRANTY; without even the implied warranty of
       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       GNU General Public License for more details.
       For a copy of the GNU General Public License see <http://www.gnu.org/licenses/>.
    property simpleFormatting : true -- when true use tt tag to enclose; when false use pre tab to enclose
    on run
      -- Write a message into the event log.
      log "  --- Starting on " & ((current date) as string) & " --- "
      set theClip to the clipboard
      if length of theClip > 33 and characters 1 thru 33 of theClip as string = "http://discussions.apple.com/post" then
           http://discussions.apple.com/post&#033;reply.jspa?messageID=9003196
       convert to:
           http://discussions.apple.com/message.jspa?messageID=9003196&#035;9003196
         set theClip to alterString(theClip, "post!reply", "message")
         set {frontPart, postNumber} to textToList(theClip, "=")
         set theClip to theClip & "#" & postNumber
      else
         --  see http://www.asciitable.com/ for the ASCII translations
         -- must be the first change so as not to cause problems.
         set theClip to alterString(theClip, "#", "&#035;")
         --  You need to use either the numeric form of the HTML symbol or
         --  translate HTML character enties as seen below.
         set theClip to alterString(theClip, "&amp;", "&amp;amp;")
         set theClip to alterString(theClip, " ", "&amp;nbsp;")
         -- Preserve blanks
         -- converts two spaces to a space and non-breaking space
         set theClip to alterString(theClip, "  ", "  ")
         set theClip to alterString(theClip, "!", "&#033;")
         set theClip to alterString(theClip, "[", "&#091;")
         set theClip to alterString(theClip, "]", "&#093;")
         set theClip to alterString(theClip, "<", "&#060;")
         set theClip to alterString(theClip, "*", "&#042;")
         set theClip to alterString(theClip, "+", "&#043;")
         set theClip to alterString(theClip, "_", "&#095;")
         set theClip to alterString(theClip, "--", "&#045;&#045;")
         set theClip to alterString(theClip, tab, "   ")
         -- suggested by red_menace from the Mac forums
         set theClip to alterString(theClip, "-", "&#45;")
         set theClip to alterString(theClip, "^", "&#94;")
         set theClip to alterString(theClip, "~", "&#126;")
         if simpleFormatting then
            set theClip to "<tt>" & theClip & "</tt>"
         else
            set theClip to addWrapper(theClip)
         end if
      end if
      set the clipboard to theClip
    end run
    on alterString(thisText, delim, replacement)
      set resultList to {}
      set {tid, my text item delimiters} to {my text item delimiters, delim}
      try
         set resultList to every text item of thisText
         set text item delimiters to replacement
         set resultString to resultList as string
         set my text item delimiters to tid
      on error
         set my text item delimiters to tid
      end try
      return resultString
    end alterString
    -- textToList was found here:
    -- http://macscripter.net/viewtopic.php?id=15423
    on textToList(thisText, delim)
      set resultList to {}
      set {tid, my text item delimiters} to {my text item delimiters, delim}
      try
         set resultList to every text item of thisText
         set my text item delimiters to tid
      on error
         set my text item delimiters to tid
      end try
      return resultList
    end textToList
    -- suggested by red_menace from the Mac forums
    -- some constants and switches
    property TextColor : "#000000" -- black  (see http://www.w3schools.com/tags/ref&#095;colornames.asp)
    property BackgroundColor : "#FFEE80" -- medium/canary yellow -- "#FFDDFF" -- a light plum/purple
    property BorderColor : "#000000" -- black
    property TheWidth : "width: 720px; " -- a width attribute
    property UseWidth : true -- use the width attribute?
    property LineCount : 25 -- the number of lines before including the height attribute
    property TheHeight : "height: " & ((LineCount * 13.6) as integer) & "px; " -- a (rough) maximum height for the formatted box
    on addWrapper(SomeText)
      fix up some formatting and add a tag wrapper  (see http://www.w3schools.com/tags/default.asp)
         parameters -      SomeText  text to add the wrapper to
         global items -   LineCount, TheHeight, UseWidth, TheWidth,  KeepFormatting,                         
                     BorderColor, TextColor, BackgroundColor
         returns [text]:      the wrapped text
      set {Height, Width} to {"", ""}
      if (count paragraphs of SomeText) is greater than LineCount then set Height to TheHeight
      if UseWidth then set Width to TheWidth
      -- hack...
      -- seems like the apple forum software doubles the returns in a pre tag
      set SomeText to alterString(SomeText, return, "<br>")
      -- change the style properties as needed
      set SomeText to "<pre style=\"
         font-family: Monaco, 'Courier New', Courier, monospace;
         font-size: 10px;
         font-weight: normal;
         margin: 0px;
         padding: 5px;
         border: 1px solid " & BorderColor & ";
         " & Width & Height & "
         color: " & TextColor & ";
         background-color: " & BackgroundColor & ";
         overflow: auto;\"
         title=\"\">" & SomeText & "</pre>
      return SomeText
    end addWrapper

    Hi,
    There is message type BANK_CREATE for posting the FI related Bank details. Using the change pointers you can trigger the idocs for posting the bank related data.
    Regards,
    Uday

  • Trying to optimize this simple query

    Hi,
    I am trying to optimize this simple query but the two methods I am trying actually make things worse.
    The original query is:
    SELECT customer_number, customer_name
    FROM bsc_pdt_account_mv
    where rownum <= 100
    AND Upper(customer_name) like '%SP%'
    AND customer_id IN
    SELECT cust_id FROM bsc_pdt_assoc_sales_force_mv
    WHERE area_identifier IN (
    SELECT area_identifier FROM bsc_pdt_assoc_sales_force_mv
    WHERE ad_identifier = '90004918' or rm_identifier = '90004918' or tm_identifier = '90004918'
    The result set of this query returns me the first 100 rows in 88 seconds and they are all distinct by default (don't know why they are distinct).
    My first attempt was to try to use table joins instead of the IN conditions:
    SELECT
    distinct -- A: I need to use distinct now
    customer_number, customer_name
    FROM bsc_pdt_account_mv pdt,
    bsc_pdt_assoc_sales_force_mv asf,
    SELECT distinct area_identifier FROM bsc_pdt_assoc_sales_force_mv
    WHERE ad_identifier = '90004918' or rm_identifier = '90004918' or tm_identifier = '90004918'
    ) area
    where
    area.area_identifier = asf.area_identifier
    AND asf.cust_id = pdt.customer_id
    AND Upper(customer_name) like '%SP%'
    AND rownum <= 100 -- B: strange when I comment this out
    order by 1
    I dont understand two things with this query. First issue, I now need to put in the distinct because the result set is not distinct by default. Second issue (very strange), when I put the rownum condition (<100) I get two rows in 1.5 seconds. If I remove the condition, I get 354 rows (whole result set) in 326 seconds.
    My second attempt was to use EXISTS instead of IN:
    SELECT
    customer_number, customer_name
    FROM bsc_pdt_account_mv pdt
    where Upper(customer_name) like '%SP%'
    AND rownum <= 100
    AND EXISTS
    select 1 from
    bsc_pdt_assoc_sales_force_mv asf,
    SELECT distinct area_identifier FROM bsc_pdt_assoc_sales_force_mv
    WHERE ad_identifier = '90004918' or rm_identifier = '90004918' or tm_identifier = '90004918'
    ) area
    where
    area.area_identifier = asf.area_identifier
    AND asf.cust_id = pdt.customer_id
    This query returns a similar distinct result set as teh original one but takes pretty much the same time (87 seconds).

    The query below hangs when run in TOAD or PL/SQL Dev. I noticed there is no rows returned from the inner table for this condition.
    SELECT customer_number, customer_name
    FROM
    bsc_pdt_account_mv pdt_account
    where rownum <= 100
    AND exists (
    SELECT pdt_sales_force.cust_id
    FROM bsc_pdt_assoc_sales_force_mv pdt_sales_force
    WHERE pdt_account.customer_id = pdt_sales_force.cust_id
    AND (pdt_sales_force.rm_identifier = '90007761' or pdt_sales_force.tm_identifier = '90007761') )
    ORDER BY customer_name
    -- No rows returned by this query
    SELECT pdt_sales_force.cust_id
    FROM bsc_pdt_assoc_sales_force_mv pdt_sales_force
    WHERE pdt_sales_force.rm_identifier = '90007761' or pdt_sales_force.tm_identifier = '90007761'

  • Why does this AppleScript run twice in Automator?

    I am trying to create an application that I can run and change the function of my F1, F2 keys to or from standard function. I found this AppleScript online and it works... but it runs twice in a row:
    tell application "System Preferences" to activate
    tell application "System Events"
    tell application "System Preferences"
    activate
    set current pane to pane "com.apple.preference.keyboard"
    end tell
    tell process "System Preferences"
    click radio button "Keyboard" of tab group 1 of window "Keyboard"
    get every attribute of checkbox ¬
    "Use all F1, F2, etc. keys as standard function keys" of ¬
    tab group 1 of window "Keyboard"
    click checkbox ¬
    "Use all F1, F2, etc. keys as standard function keys" of ¬
    tab group 1 of window "Keyboard"
    activate
    if value of checkbox ¬
    "Use all F1, F2, etc. keys as standard function keys" of ¬
    tab group 1 of window "Keyboard" = 0 then
    display dialog ¬
    "Standard Function Keys off..." giving up after 1
    else
    display dialog ¬
    "Standard Function Keys on..." giving up after 1
    end if
    end tell
    tell application "System Preferences"
    quit
    end tell
    end tell
    If I change the Script by taking out the following, it only runs once. I believe my issue is in the below Script. I have fiddled with all that I know how to and either it doesn't run, or it runs twice...
    tell process "System Preferences"
    click radio button "Keyboard" of tab group 1 of window "Keyboard"
    get every attribute of checkbox ¬
    "Use all F1, F2, etc. keys as standard function keys" of ¬
    tab group 1 of window "Keyboard"
    click checkbox ¬
    "Use all F1, F2, etc. keys as standard function keys" of ¬
    tab group 1 of window "Keyboard"
    activate
    if value of checkbox ¬
    "Use all F1, F2, etc. keys as standard function keys" of ¬
    tab group 1 of window "Keyboard" = 0 then
    display dialog ¬
    "Standard Function Keys off..." giving up after 1
    else
    display dialog ¬
    "Standard Function Keys on..." giving up after 1
    end if
    end tell
    Any suggestions would help. If you run it and it only runs once, I am at a loss. Thank you for you time.

    it works fine for me in both automator and applescript. are you sure you didn't enter it twice in the Run Applescript workflow?
    a couple of tweaks, more for clarity than anything else:
              tell application "System Preferences"
                        activate
                        set current pane to pane "com.apple.preference.keyboard"
              end tell
              tell application "System Events"
                        tell process "System Preferences"
                                  click radio button "Keyboard" of tab group 1 of window "Keyboard"
                                  get every attribute of checkbox ¬
                                            "Use all F1, F2, etc. keys as standard function keys" of ¬
                                            tab group 1 of window "Keyboard"
                                  click checkbox ¬
                                            "Use all F1, F2, etc. keys as standard function keys" of ¬
                                            tab group 1 of window "Keyboard"
                                  activate
                                  if value of checkbox ¬
                                            "Use all F1, F2, etc. keys as standard function keys" of ¬
                                            tab group 1 of window "Keyboard" = 0 then
                                            display dialog ¬
                                                      "Standard Function Keys off..." giving up after 1
                                  else
                                            display dialog ¬
                                                      "Standard Function Keys on..." giving up after 1
                                  end if
                        end tell
                        tell application "System Preferences"
                                  quit
                        end tell
              end tell

  • How to modify this AppleScript to work with Safari 7.0?

    I have been using this AppleScript as an Automator service in order to get Safari to close all tabs to the right of the current tab. However I have updated to Mavericks (10.9) and find that this no longer works.
    Can anyone advise how this AppleScript should be changed in order to make it work again?

    The script does still work: just needed a restart. A more concise version of the script is available here.

  • How to optimize this select statement  its a simple select....

    how to optimize this select statement  as the records in earlier table is abt i million
    and this simplet select statement is not executing and taking lot of time
      SELECT  guid  
                    stcts      
      INTO table gt_corcts
      FROM   corcts
      FOR all entries in gt_mege
      WHERE  /sapsll/corcts~stcts = gt_mege-ctsex
      and /sapsll/corcts~guid_pobj = gt_Sagmeld-guid_pobj.
    regards
    Arora

    Hi Arora,
    Using Package size is very simple and you can avoid the time out and as well as the problem because of memory.  Some time if you have too many records in the internal table, then you will get a short dump called TSV_TNEW_PAGE_ALLOC_FAILED.
    Below is the sample code.
    DATA p_size = 50000
    SELECT field1 field2 field3
       INTO TABLE itab1 PACKAGE SIZE p_size
       FROM dtab
       WHERE <condition>
    Other logic or process on the internal table itab1
    FREE itab1.
    ENDSELECT.
    Here the only problem is you have to put the ENDSELECT.
    How it works
    In the first select it will select 50000 records ( or the p_size you gave).  That will be in the internal table itab1.
    In the second select it will clear the 50000 records already there and append next 50000 records from the database table.
    So care should be taken to do all the logic or process with in select and endselect.
    Some ABAP standards may not allow you to use select-endselect.  But this is the best way to handle huge data without short dumps and memory related problems. 
    I am using this approach.  My data is much more huge than yours.  At an average of atleast 5 millions records per select.
    Good luck and hope this help you.
    Regards,
    Kasthuri Rangan Srinivasan

  • Performance Tuning Issues  ( How to Optimize this Code)

    _How to Optimize this Code_
    FORM MATL_CODE_DESC.
      SELECT * FROM VBAK WHERE VKORG EQ SAL_ORG AND
                               VBELN IN VBELN AND
                               VTWEG IN DIS_CHN AND
                               SPART IN DIVISION AND
                               VKBUR IN SAL_OFF AND
                               VBTYP EQ 'C' AND
                               KUNNR IN KUNNR AND
                               ERDAT BETWEEN DAT_FROM AND DAT_TO.
        SELECT * FROM VBAP WHERE VBELN EQ VBAK-VBELN AND
                                 MATNR IN MATNR.
          SELECT SINGLE * FROM MAKT WHERE MATNR EQ VBAP-MATNR.
          IF SY-SUBRC EQ 0.
            IF ( VBAP-NETWR EQ 0 AND VBAP-UEPOS NE 0 ).
              IF ( VBAP-UEPVW NE 'B' AND VBAP-UEPVW NE 'C' ).
                MOVE VBAP-VBELN TO ITAB1-SAL_ORD_NUM.
                MOVE VBAP-POSNR TO ITAB1-POSNR.
                MOVE VBAP-MATNR TO ITAB1-FREE_MATL.
                MOVE VBAP-KWMENG TO ITAB1-FREE_QTY.
                MOVE VBAP-KLMENG TO ITAB1-KLMENG.
                MOVE VBAP-VRKME TO ITAB1-FREE_UNIT.
                MOVE VBAP-WAVWR TO ITAB1-FREE_VALUE.
                MOVE VBAK-VTWEG TO ITAB1-VTWEG.
                MOVE VBAP-UEPOS TO ITAB1-UEPOS.
              ENDIF.
            ELSE.
              MOVE VBAK-VBELN TO ITAB1-SAL_ORD_NUM.
              MOVE VBAK-VTWEG TO ITAB1-VTWEG.
              MOVE VBAK-ERDAT TO ITAB1-SAL_ORD_DATE.
              MOVE VBAK-KUNNR TO ITAB1-CUST_NUM.
              MOVE VBAK-KNUMV TO ITAB1-KNUMV.
             SELECT SINGLE * FROM KONV WHERE KNUMV EQ VBAK-KNUMV AND
                                             KSTEU = 'C' AND
                                             KHERK EQ 'A' AND
                                             KMPRS = 'X'.
             IF SY-SUBRC EQ 0.
               ITAB1-REMARKS = 'Manual Price Change'.
             ENDIF.
              SELECT SINGLE * FROM KONV WHERE KNUMV EQ VBAK-KNUMV AND
                                              KSTEU = 'C' AND
                                              KHERK IN ('C','D') AND
                                              KMPRS = 'X' AND
                                              KRECH IN ('A','B').
              IF SY-SUBRC EQ 0.
                IF KONV-KRECH EQ 'A'.
                  MOVE : KONV-KSCHL TO G_KSCHL.
                  G_KBETR = ( KONV-KBETR / 10 ).
                  MOVE G_KBETR TO G_KBETR1.
                  CONCATENATE G_KSCHL G_KBETR1 '%'
                              INTO ITAB1-REMARKS SEPARATED BY SPACE.
                ELSEIF KONV-KRECH EQ 'B'.
                  MOVE : KONV-KSCHL TO G_KSCHL.
                  G_KBETR = KONV-KBETR.
                  MOVE G_KBETR TO G_KBETR1.
                  CONCATENATE G_KSCHL G_KBETR1
                              INTO ITAB1-REMARKS SEPARATED BY SPACE.
                ENDIF.
              ELSE.
                ITAB1-REMARKS = 'Manual Price Change'.
              ENDIF.
              CLEAR : G_KBETR, G_KSCHL,G_KBETR1.
              MOVE VBAP-KWMENG TO ITAB1-QTY.
              MOVE VBAP-VRKME TO ITAB1-QTY_UNIT.
              IF VBAP-UMVKN NE 0.
                ITAB1-KLMENG = ( VBAP-UMVKZ / VBAP-UMVKN ) * VBAP-KWMENG.
              ENDIF.
              IF ITAB1-KLMENG NE 0.
                VBAP-NETWR = ( VBAP-NETWR / VBAP-KWMENG ).
                MOVE VBAP-NETWR TO ITAB1-INV_PRICE.
              ENDIF.
              MOVE VBAP-POSNR TO ITAB1-POSNR.
              MOVE VBAP-MATNR TO ITAB1-MATNR.
              MOVE MAKT-MAKTX TO ITAB1-MAKTX.
            ENDIF.
            SELECT SINGLE * FROM VBKD WHERE VBELN EQ VBAK-VBELN AND
                                            BSARK NE 'DFUE'.
            IF SY-SUBRC EQ 0.
              ITAB1-INV_PRICE = ITAB1-INV_PRICE * VBKD-KURSK.
              APPEND ITAB1.
              CLEAR ITAB1.
            ELSE.
              CLEAR ITAB1.
            ENDIF.
          ENDIF.
        ENDSELECT.
      ENDSELECT.
    ENDFORM.                               " MATL_CODE_DESC

    Hi Vijay,
    You could start by using INNER JOINS:
    SELECT ......
                FROM (                    VBAK
                             INNER JOIN VBAP
                                           ON VBAPVBELN = VBAKVBELN
                             INNER JOIN MAKT
                                           ON MAKTMATNR = VBAPMATNR AND
                                                 MAKT~SPRAS = SYST-LANGU )
                INTO TABLE itab
              WHERE VBAK~VBELN IN VBELN
                   AND VBAK~VTWEG IN DIS_CHN
                   AND VBAK~SPART IN DIVISION
                   AND VBAK~VKBUR IN SAL_OFF
                   AND VBAK~VBTYP EQ 'C'
                   AND VBAK~KUNNR IN KUNNR
                   AND VBAK~ERDAT BETWEEN DAT_FROM AND DAT_TO
                   AND VBAP~NETWR EQ 0
                   AND VBAP~UEPOS NE 0
    Regards,
    John.

  • Optimize this

    Hi,
    how can we optimize this code?
      SELECT mara~matnr  "Material NO
             matkl  "Material group
             wrkst  "Basic Material
             prdha  "Product hierarchy
             marc~werks   "Plant
             fevor   "Production Scheduler
             dismm   "MRP Type
             dispo   "MRP Controller
             plifz   "planned delivery time in days
             ekgrp   "Purchasing Group
             beskz   "Procurement Type
             prctr   "Profit Center
             FROM mara INNER JOIN marc
             ON mara~matnr = marc~matnr
             INTO TABLE itab_marc
             WHERE mara~matnr IN s_matnr
             AND werks IN s_plant
             AND fevor IN s_schdlr
             AND dispo IN s_mrp
             AND ekgrp IN s_purgrp
             AND beskz IN s_prtype
             AND prdha IN s_proj.
      IF sy-subrc EQ 0.
        SORT itab_marc BY matnr werks fevor dispo ekgrp ekgrp beskz.
      ENDIF.
      IF itab_marc[] IS NOT INITIAL.
        SELECT matnr  "Material No
               bwkey  "Plant
               bwtar
               vprsv  "Price control indicator
               verpr  "Moving Average Price/Periodic Unit Price
               stprs  "Standard price
               peinh  "Price unit
               FROM mbew
               INTO TABLE itab_mbew
               FOR ALL ENTRIES IN itab_marc
              WHERE matnr EQ itab_marc-matnr
              AND bwkey EQ itab_marc-werks.
        IF sy-subrc EQ 0.
          SORT itab_mbew BY matnr bwkey.
        ENDIF.
      ENDIF.
      IF itab_marc[] IS NOT INITIAL.
        SELECT   matnr     "Material No
                 werks     "Plant
                 lgort     "Storage Location
                 labst     "Valuated stock with unrestricted use
                 umlme     "Stock in transfer
                 insme     "Stock in quality inspection
                 einme     "Total Stock of All Restricted Batches
                 speme     "blocked state
                 retme     "Blocked state return
                 klabs     "Unrestricted-use consignment stock
                 kinsm     "Consignment stock in quality inspection
                 FROM mard
                 INTO TABLE itab_mard
                 FOR ALL ENTRIES IN itab_marc
                 WHERE matnr EQ itab_marc-matnr
                 AND werks   EQ itab_marc-werks.
        IF sy-subrc EQ 0.
          SORT itab_mard BY matnr werks.
        ENDIF.
      ENDIF.
    Kate

    I have 2 proposals.
    First to make it more readable, write mara as a marc as b and denote each field with a~ or b~ in field list and where condition.
    You should sort the internal tables by the full key, i.e. also bwtar and also lgort.
    And if possible use sorted tables with unique keys.
    Siegfried

  • I don't know how I can optimize this SQL

    Dear ALL:
    I don't know how I can optimize this SQL.
    Is it possible to make a better SQL or PL/SQL?
    Please let me know your good thought.
    Thank you.
    Sincerely,
    ===========================================================
    (SELECT     A, B, C, SUM(D) as D, AVG(E) as E
    FROM      T1, T2
    WHERE     T1.timestamp BETWEEN TO_DATE('00:00:00','HH24:MI:SS')
    AND TO_DATE('01:00:00','HH24:MI:SS')
    GROUP BY A, B, C
    UNION ALL
    (SELECT     A, B, C, SUM(D) as D, AVG(E) as E
    FROM      T1, T2
    WHERE     T1.timestamp BETWEEN TO_DATE('01:00:01','HH24:MI:SS')
    AND TO_DATE('02:00:00','HH24:MI:SS')
    GROUP BY A, B, C
    UNION ALL
    (SELECT     A, B, C, SUM(D) as D, AVG(E) as E
    FROM      T1, T2
    WHERE     T1.timestamp BETWEEN TO_DATE('02:00:01','HH24:MI:SS')
    AND TO_DATE('03:00:00','HH24:MI:SS')
    GROUP BY A, B, C
    UNION ALL
    (SELECT     A, B, C, SUM(D) as D, AVG(E) as E
    FROM      T1, T2
    WHERE     T1.timestamp BETWEEN TO_DATE('03:00:01','HH24:MI:SS')
    AND TO_DATE('04:00:00','HH24:MI:SS')
    GROUP BY A, B, C
    ORDER BY A ASC, B ASC, C ASC
    ===========================================================

    Dear Warren:
    Actually, for this query, it takes a few second to complete the query.
    But, I have to create several time period and I have to optimize the SQL.
    Time period is 1 hour, 30 min, 15 min, 5 min.
    That is,
    ===========================================================
    WHERE T1.timstamp BETWEEN TO_DATE('00:00:00','HH24:MI:SS')
    AND TO_DATE('01:00:00','HH24:MI:SS')
    UNION ALL
    WHERE T1.timestamp BETWEEN TO_DATE('23:00:01','HH24:MI:SS')
    AND TO_DATE('24:00:00','HH24:MI:SS')
    ===========================================================
    WHERE T1.timstamp BETWEEN TO_DATE('00:00:00','HH24:MI:SS')
    AND TO_DATE('00:30:00','HH24:MI:SS')
    UNION ALL
    WHERE T1.timestamp BETWEEN TO_DATE('23:30:01','HH24:MI:SS')
    AND TO_DATE('24:00:00','HH24:MI:SS')
    ===========================================================
    WHERE T1.timstamp BETWEEN TO_DATE('00:00:00','HH24:MI:SS')
    AND TO_DATE('00:15:00','HH24:MI:SS')
    UNION ALL
    WHERE T1.timestamp BETWEEN TO_DATE('23:45:01','HH24:MI:SS')
    AND TO_DATE('24:00:00','HH24:MI:SS')
    ===========================================================
    WHERE T1.timstamp BETWEEN TO_DATE('00:00:00','HH24:MI:SS')
    AND TO_DATE('00:05:00','HH24:MI:SS')
    UNION ALL
    WHERE T1.timestamp BETWEEN TO_DATE('23:55:01','HH24:MI:SS')
    AND TO_DATE('24:00:00','HH24:MI:SS')
    ===========================================================
    Do you know how this SQL is optimized?
    Thank you,

  • How can i optimize this SQL

    Is there anyway i could optimize the below mentioned SQL. Since our test DB is down now, i'll be posting the EXPLAIN PLAN later.
    Is there anything i could do syntactically to optimize this sql?
    SELECT SUBSTR(STK_INF.TASK_GENRTN_REF_NBR,1,12) AS PICK_WAVE_NBR,
                     ( CASE WHEN ( SUM(STK_INF.QTY_ALLOC) > 0 ) THEN
            ROUND ( (SUM(CASE WHEN (STK_INF.NEXT_TASK_ID = 0 AND STK_INF.ALLOC_INVN_DTL_ID = 0) THEN
            STK_INF.QTY_ALLOC ELSE 0 END ) / (SUM(STK_INF.QTY_ALLOC))),2 ) * 100
            ELSE 0 END ) AS PICK_PER,
         ( CASE WHEN ( SUM(STK_INF.QTY_ALLOC) > 0 ) THEN
           ROUND( (SUM(CASE WHEN (STK_INF.NEXT_TASK_ID = 0 AND STK_INF.ALLOC_INVN_DTL_ID = 0) THEN
           STK_INF.QTY_PULLD ELSE 0 END ) / (SUM(STK_INF.QTY_ALLOC))),2 ) * 100
           ELSE 0 END ) AS TILT_PERCENT
         FROM STK_INF, TRK_DTL
         WHERE STK_INF.TASK_GENRTN_REF_CODE = '44' AND STK_INF.CARTON_NBR IS NOT NULL
          AND ((STK_INF.NEXT_TASK_ID = 0 AND STK_INF.STAT_CODE <= 90) OR (STK_INF.NEXT_TASK_ID > 0 AND STK_INF.STAT_CODE < 99))
          AND PULL_LOCN_ID = TRK_DTL.LOCN_ID(+) AND (TRK_DTL.AREA <>'C' OR TRK_DTL.AREA IS NULL)
         GROUP BY SUBSTR(STK_INF.TASK_GENRTN_REF_NBR,1,12)

    This is the EXPLAIN PLAIN i got after i issued EXECUTE DBMS_STATS.GATHER_TABLE_STATS ('schema_name','table_name'); for both the tables involved.
    The number of row returned is still 222 rows. But in the EXPLAIN PLAN it is shown as 3060 !!
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3267659036
    | Id  | Operation               | Name     | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT        |          |  3060 |   194K|       | 16527  (10)| 00:03:19 |
    |   1 |  HASH GROUP BY          |          |  3060 |   194K|       | 16527  (10)| 00:03:19 |
    |*  2 |   FILTER                |          |       |       |       |            |          |
    |*  3 |    HASH JOIN RIGHT OUTER|          |   177K|    11M|  7344K| 16397  (10)| 00:03:17 |
    |   4 |     TABLE ACCESS FULL   | TRK_DTL |   313K|  3669K|       |  2378   (6)| 00:00:29 |
    |*  5 |     TABLE ACCESS FULL   | STK_INF |   177K|  9205K|       | 13030  (11)| 00:02:37 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       2 - filter("TRK_DTL"."AREA"<>'C' OR "TRK_DTL"."AREA" IS NULL)
       3 - access("PULL_LOCN_ID"="TRK_DTL"."LOCN_ID"(+))
       5 - filter("STK_INF"."CARTON_NBR" IS NOT NULL AND
                  "STK_INF"."TASK_GENRTN_REF_CODE"='44' AND ("STK_INF"."NEXT_TASK_ID"=0 AND
                  "STK_INF"."STAT_CODE"<=90 OR "STK_INF"."NEXT_TASK_ID">0 AND
                  "STK_INF"."STAT_CODE"<99))
    22 rows selected.You mentioned about creating indexes in STK_INF table. STK_INF.NEXT_TASK_ID has 186385 distinct values out of a total 782087. Does NEXT_TASK_ID make a good candidate for a B-Tree index
    STK_INF.STAT_CODE has only four distinct values, would this make a good candidate for a Bitmap index?

  • How I can optimize this SQL query

    I require your help, I want to know how I can optimize this query
    SELECT
                    "F42119". "SDLITM" as "Code1"
                    "F42119". "SDAITM" as "Code2"
                    "F42119". "SDDSC1" as "Product"
                    "F42119". "SDMCU" as "Bodega"
                    Sum ("F42119". "SDSOQS" / 10000) as "Number",
                    Sum ("F42119". "SDUPRC" / 10000) as "preciou"
                    Sum ("F42119". "SDAEXP" / 100) as "Value",
                    Sum ("F42119". "SDUNCS" / 10000) as "CostoU"
                    Sum ("F42119". "SDECST" / 100) as "Cost"
                    "F4101". "IMSRP1" as "Division"
                    "F4101". "IMSRP2" as "classification",
                    "F4101". "IMSRP8" as "Brand"
                    "F4101". "IMSRP9" as "Aroma"
                    "F4101". "IMSRP0" as "Presentation"
                    "F42119". "SDDOC" as "Type",
                    "F42119". "SDDCT" as "Document",
                    "F42119". "SDUOM" as "Unit"
                    "F42119". "SDCRCD" as "currency"
                    "F0101". "ABAN8" as "ABAN8"
                    "F0101". "ABALPH" as "Customer"
                    "F0006". "MCRP22" as "Establishment"
    from          "PRODDTA". "F0101" "F0101"
                    "PRODDTA". "F42119" "F42119"
                    "PRODDTA". "F4101" "F4101"
                    "PRODDTA". "F0006" "F0006"
    where       "F42119". "SDAN8" = "F0101". "ABAN8"
      and         "F0006". "MCMCU" = "F42119". "SDMCU"
      and         "F4101". "IMITM" = "F42119". "SDITM"
      and         "F42119". "SDDCT" in ('RI', 'RM', 'RN')
      and         CAST (EXTRACT (MONTH FROM TO_DATE (substr ((to_date ('01-01-'| | to_char (round (1900 + (CAST ("F42119". "SDDGL" as int) / 1000))),' DD- MM-                YYYY ') + substr (to_char (CAST ("F42119". "SDDGL" as int)), 4,3) -1), 1,10))) AS INT) in : Month
    and          CAST (EXTRACT (YEAR FROM TO_DATE (substr ((to_date ('01-01-'| | to_char (round (1900 + (CAST ("F42119". "SDDGL" as int) / 1000))),' DD- MM-                YYYY ')+ Substr (to_char (CAST ("F42119". "SDDGL" as int)), 4,3) -1), 1,10))) AS INT) in: Year
    and          trim ("F0006". "MCRP22") =: Establishment
    and          trim ("F4101". "IMSRP1") =: Division
    Group By    "F42119". "SDLITM"
                    "F42119". "SDAITM"
                    "F42119". "SDDSC1"
                    "F4101". "IMSRP1"
                    "F42119". "SDDOC"
                    "F42119". "SDDCT"
                    "F42119". "SDUOM"
                    "F42119". "SDCRCD"
                    "F0101". "ABAN8"
                    "F0101". "ABALPH"
                    "F4101". "IMSRP2"
                    "F4101". "IMSRP8"
                    "F4101". "IMSRP9"
                    "F4101". "IMSRP0"
                    "F42119". "SDMCU"
                    "F0006". "MCRP22"
    I appreciate the help you can give me

    It seems to me that part of fixing it could be how you join the tables.
    Instead of the humongous where clause, put the applicable conditions on the join.
    You have
    from "PRODDTA". "F0101" "F0101"
    "PRODDTA". "F42119" "F42119"
    "PRODDTA". "F4101" "F4101"
    "PRODDTA". "F0006" "F0006"
    where "F42119". "SDAN8" = "F0101". "ABAN8"
    and "F0006". "MCMCU" = "F42119". "SDMCU"
    and "F4101". "IMITM" = "F42119". "SDITM"
    and "F42119". "SDDCT" in ('RI', 'RM', 'RN')
    and CAST (EXTRACT (MONTH FROM TO_DATE (substr ((to_date ('01-01-'| | to_char (round (1900 + (CAST ("F42119". "SDDGL" as int) / 1000))),' DD- MM- YYYY ') + substr (to_char (CAST ("F42119". "SDDGL" as int)), 4,3) -1), 1,10))) AS INT) in : Month
    and CAST (EXTRACT (YEAR FROM TO_DATE (substr ((to_date ('01-01-'| | to_char (round (1900 + (CAST ("F42119". "SDDGL" as int) / 1000))),' DD- MM- YYYY ')+ Substr (to_char (CAST ("F42119". "SDDGL" as int)), 4,3) -1), 1,10))) AS INT) in: Year
    and trim ("F0006". "MCRP22") =: Establishment
    and trim ("F4101". "IMSRP1") =: Division
    INSTEAD try something like
    from JOIN "PRODDTA". "F0101" "F0101" ON "F42119". "SDAN8" = "F0101". "ABAN8"
    JOIN "PRODDTA". "F42119" "F42119" ON "F0006". "MCMCU" = "F42119". "SDMCU"
    JOIN "PRODDTA". "F4101" "F4101" ON join condition
    JOIN "PRODDTA". "F0006" "F0006" ON join condition.
    Not sure exactly how you need things joined, but above is the basic idea. Remove criteria for joining the tables from the WHERE clause and put them
    in the join statements. That might clean things up and make it more efficient.

  • Can anyone tell me how can i optimize this query...

    Can anyone tell me how can i optimize this query ??? :
    Select Distinct eopersona.numident From rscompeten , rscompet , rscv , eopersona , rscurso , rseduca , rsexplab , rsinteres
    Where ( ( (LOWER (rscompeten.nombre LIKE '%caracas%') AND ( rscompeten.id = rscompet.idcompeten ) AND ( rscv.id = rscompet.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rscurso.nombre) LIKE '%caracas%') AND ( rscv.id = rscurso.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rscurso.lugar) LIKE '%caracas%') AND ( rscv.id = rscurso.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rseduca.univinst) LIKE '%caracas%)' AND ( rscv.id = rseduca.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rsexplab.nombempre) LIKE '%caracas%' AND ( rscv.id = rsexplab.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rsinteres.descrip) LIKE '%caracas%' AND ( rscv.id = rsinteres.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rscv.cargoasp) LIKE '%caracas%' AND ( eopersona.id = rscv.idpersona ) )
    OR ( LOWER (eopersona.ciudad) LIKE '%caracas%' AND ( eopersona.id = rscv.idpersona )
    PLEASE IF YOU FIND SOMETHING WRONG.. PLEASE HELP ME.. this query takes me aproximatelly 10 minutes and the database is really small ( with only 200 records on each table )

    You are querying eight tables, however in any of your OR predicates you're only restricting 3 or 4 of those tables. That means that the remaining 4 or 5 tables are generating cartesian products. (n.b. the cartesian product of 5 tables with 200 rows each results in g 200^5 = 320,000,000,000 rows) Then you casually hide this behind "distinct".
    A simple restatement of your requirements looks like this:
    Select eopersona.numident
      From rscompeten,
           rscompet,
           rscv,
           eopersona
    Where LOWER (rscompeten.nombre) LIKE '%caracas%'
       AND rscompeten.id = rscompet.idcompeten
       AND rscv.id = rscompet.idcv
       AND eopersona.id = rscv.idpersona
    UNION
    Select eopersona.numident
      From rscurso ,
           rscv,
           eopersona
    Where LOWER (rscurso.nombre) LIKE '%caracas%'
       AND rscv.id = rscurso.idcv
       AND eopersona.id = rscv.idpersona
    UNION
    Select eopersona.numident
      From rscurso ,
           rscv,
           eopersona
    Where LOWER (rscurso.lugar) LIKE '%caracas%'
       AND rscv.id = rscurso.idcv
       AND eopersona.id = rscv.idpersona
    UNION
    ...From there you can eliminate redundancies as desired, but I imagine that the above will perform admirably with the data volumes you describe.

  • How can I make this AppleScript available as a control click menu?

    This code was previously created in another question from 2009 (https://discussions.apple.com/thread/1881786?start=15&tstart=0), but the last person to comment on it was never given an answer. I wanted to see if this following AppleScript could be used as a control-click menu, so when I click on a folder, I can choose to run this script so set an icon as the folder image, instead of having to select both the image and the location. In other words, can I have a one-click method to set, say "cover.jpg" or "1.jpg" as the folder icon? Any help is appreciated.
    Here is the code that works through the use of selecting the file and the folder:
    --CODE (for AppleScript Studio script)
    set srcpath to POSIX path of (choose file with prompt "Choose source image file.")
    set dstpath to POSIX path of (choose folder with prompt "Choose target folder.")
    --set dstpath to dstpath's text 1 thru -2 -- remove last slash if necessary.
    setIcon(srcpath, dstpath)
    on setIcon(srcpath, dstpath)
    set nsimg to load image srcpath
    set nswks to call method "sharedWorkspace" of class "NSWorkspace"
    set r to call method "setIcon:forFile:options:" of nswks with parameters {nsimg, dstpath, 0}
    delete nsimg
    return r
    end setIcon
    --END OF CODE

    Jules,
    Depending on the shape, and upon the appearance (varying width and/or knotting or whatever), it may be anything from a Rectangular/Polar Grid (bundled with the Line Segment Tool) to something intricate and difficult.

  • Why does this AppleScript cause a big delay in Mavericks?

    Hello,
    I use FileMaker for my database needs. I have been using an AppleScript to create a calendar event from FM to my Calendar using Apple Calendar. This has worked flawlewssly in Mac oSX 10.7 and 10.8. Every since Mavericks, the script still works (creating no error) but takes about 1 minute to complete. The funny thing is that if I run the script from the AS editor, it works just fine. The FileMaker does have access to my calendar in the security area.
    Any thoughts?
    Here is the script that is invoked:
    launch application "Calendar"
    repeat until application "Calendar" exists
              "delay 1"
    end repeat
    tell application "Calendar"
              set my_event to make new event at end of events of calendar "Test Calendar" with properties {description:"Test description here", summary:"Summary Text here", location:"location information here", start date:date "Sunday, December 8, 2013 at 10:00:00 AM", end date:date "Sunday, December 8, 2013 at 12:00:00 PM", allday event:false}
    end tell
    Thanks!
    Stephen

    set myCal to "MyLocalendar"
    tell application "Calendar"
              set l to the title of every calendar
              if myCal is not in l then
                        set n to uid of (make new calendar with properties {name:myCal})
              end if
    end tell

  • Please help me optimize this

    1. This code fragment:
    declare
    procedure t(ent in varchar)
    is
    begin
    for reg in (
    select
    /*+nocache*/
    opds_psap_numero,
    min(opds_data_inicio_tarde) as opds_data_inicio_tarde
    from operacoes_diagrama_sap, projeto_sap
    where
    opds_psap_numero = psap_numero and
    psap_pep like ent
    group by
    opds_psap_numero
    ) loop
    dbms_output.put_line('just teste');
    end loop;
    end;
    begin
    t('PR42E-075001%');
    end;
    Execution Time
    ***SCRIPT START 29-mar-2007 17:33:25 ***
    ***SCRIPT END 29-mar-2007 17:35:13 ***
    Time = 2 minutes (aprox)
    ==============================================
    2. But this code fragment (the same as before but with static sql):
    declare
    procedure t(ent in varchar)
    is
    begin
    for reg in (
    select
    /*+nocache*/
    opds_psap_numero,
    min(opds_data_inicio_tarde) as opds_data_inicio_tarde
    from operacoes_diagrama_sap, projeto_sap
    where
    opds_psap_numero = psap_numero and
    psap_pep like 'PR42E-075001%'
    group by
    opds_psap_numero
    ) loop
    dbms_output.put_line('just teste');
    end loop;
    end;
    begin
    t('PR42E-075001%');
    end;
    Execution Time
    ***SCRIPT START : 29-mar-2007 17:39:29***
    ***SCRIPT END 29-mar-2007 17:39:30***
    Time 1 sec
    ================================================
    I need the code of the first example (I must pass an 'in" parameter to the procedure), but with performance of the second.
    This query runs very fast when posted in sqlnavigator.
    it returns approx 1000 lines and i have an index at projeto_sap.psap_pep field
    What am i doing wrong?
    Please if you dont understand let me know. English is not my first language. From hot Brazil hehe

    Your second fragment has a string literal 'PR42E-075001%' for the LIKE operator in your WHERE clause. The first fragment uses a PL/SQL parameter, effectively a bind variable.
    The optimizer can choose the index for the second fragment because it knows the index will be effective. But the first fragment could have any value for the variable. The optimizer chooses a path that is best for "any value" AND YOU WIND UP WITH A PLAN THAT ...
    Hmm, I hit the caps lock by accident there, but it seems strangely appropriate.
    Anyway, you can try adding a hint to your query:
    /*+ nocache index( projeto_sap index_name */

Maybe you are looking for