How can I optimize this script?

What I don't like about this script:
1) It has to be run multiple times to process multiple staff. I'd prefer if I could input multiple employee numbers at once
2) It takes so long to search for the user. If I use the script, it can currently take 30s to find the employee. When I use ADUC to run the "(&(objectCategory=user)(objectClass=user)(employeeID=17688))" search, the results are immediate.
3) I'd like it to look through all the chosen employee numbers before replicating the domain.
4) The end of the powershell script calls a batch file because the syntax in the batch file didn't work in powershell. Can the batch file commands be included directly in the powershells script?
5) The batch file references all of our DC's to minimize replication latency. Can it be simplified while ensuring all DC's are hit ASAP?
Here is the powershell script:
#Disable User# Add the Quest ActiveRoles Management Shell snap-in to recognize extended commands
Add-PSSnapin Quest.ActiveRoles.ADManagement
# Take first commandline argument which is the employeeID and assign it to the $empID variable
$empID=$Args[0]
# Search for the EmployeeID and find the matching NTAccountName (NBDomain\*) [This takes about 30 seconds for 1400 users]
Write-Host "Searching for the User which matches Employee ID $EmpID, you have about 30 seconds to press Ctrl-C to cancel..."
$user = get-qaduser -includedproperties employeeID,samaccountname -sizelimit 0 | where {$_.employeeID -eq $empID}
# Find the matching SAMAccountname
$samaccountname = $user.samaccountname
# Find the matching DN
$SourceDN = $user.dn
# Set where the disabled account will be moved
$DestDN = "OU=Disabled Accounts,DC=domain,DC=Com"
# Set recipient limits to 0
set-mailbox -identity $samaccountname -recipientlimits 0
Write-host $User Recipient Limit set to 0.
# Disable all mailbox features except archive
set-casmailbox -identity $samaccountname -owaenabled $false -ewsenabled $false -ecpenabled $false -mapienabled $false -mapiblockoutlookrpchttp $true -ewsallowmacoutlook $false -ewsallowoutlook $false
set-casmailbox -identity $samaccountname -activesyncenabled $false -popenabled $false -imapenabled $false
Write-host $User Exchange features disabled.
# Block all devices associated with the mailbox:
$DeviceIDs = (Get-ActiveSyncDeviceStatistics -Mailbox $SourceDN | foreach { $_.DeviceID } )
Set-CASMailbox -Identity $SourceDN -ActiveSyncBlockedDeviceIDs $DeviceIDs
Write-Host $User All approved devices have been blocked.
# Remove all devices associated with the mailbox:
Set-casmailbox -identity $samaccountname -ActiveSyncAllowedDeviceIDs $null
Write-Host $User All ActiveSync devices removed from mailbox.
#Disable the user
Disable-QADUser $user
Write-Host $user account disabled.
# Move the user to the Disabled OU
Dsmove $SourceDN -newparent $DestDN
Write-Host $User account moved to Disabled OU.
Write-host Finished processing user $User
Write-host ""
Write-host "Replicating the enterprise domain across sites..."
cd "C:\Users\username\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\Admin Tools"
.\"Force DC replication.cmd"
cd "c:\scripts"
pause

Here's the script I'm happy with. It's just .\scriptname.ps1 xxxx xxxy xxxz, where the args are employee numbers.
#Disable User
import-module activedirectory
cls
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",""
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",""
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)
foreach ($empID in $args)
# Search for the EmployeeID and find the matching NTAccountName (domain\*)
$user=get-aduser -properties employeeID,samaccountname -resultsetsize $null -LDAPFilter "(employeeID=$empID)"
$samaccountname = $user.samaccountname
$DN=$user.distinguishedname
$name=$user.name
$caption = "Warning!"
$message = "Do you want to disable " + $name + "?"
$result = $Host.UI.PromptForChoice($caption,$message,$choices,0)
if($result -eq 1) { Write-Host "Skipping to the next name (if available)" }
if($result -eq 1) { continue}
if($result -eq 0) { Write-Host "----------"}
if($result -eq 0) { Write-Host "Processing $name"}
# Set recipient limits to 0
set-mailbox -identity $samAccountName -recipientlimits 0
Write-host "$name Recipient Limit set to 0."
# Disable all mailbox features except archive
set-casmailbox -identity $samaccountname -owaenabled $false -ewsenabled $false -ecpenabled $false -mapienabled $false -mapiblockoutlookrpchttp $true -ewsallowmacoutlook $false -ewsallowoutlook $false
set-casmailbox -identity $samaccountname -activesyncenabled $false -popenabled $false -imapenabled $false
Write-host "$name Exchange features disabled."
# Block all devices associated with the mailbox:
$DeviceIDs = (Get-ActiveSyncDeviceStatistics -Mailbox $dn | foreach { $empID.DeviceID } )
Set-CASMailbox -Identity $DN -ActiveSyncBlockedDeviceIDs $DeviceIDs
Write-Host "$name All approved devices have been blocked."
# Remove all devices associated with the mailbox:
Set-casmailbox -identity $samAccountName -ActiveSyncAllowedDeviceIDs $null
Write-Host "$name All ActiveSync devices removed from mailbox."
#Disable the user
set-aduser $samAccountname -Enabled $false
Write-Host "$name account disabled."
# Move the user to the Disabled OU
Move-ADObject -TargetPath "OU=Disabled Accounts,DC=domain,DC=Com" -Identity $dn
Write-Host "$name account moved to Disabled OU."
Write-host "Finished processing user $name."
Write-host "----------"
# Recycle the IIS Application Pools to clear the token cache
Write-Host "Recycling IIS Application pools to clear the token cache..."
$pools=Get-WMIObject IISApplicationPool -Namespace root\MicrosoftIISv2 -authentication Packetprivacy -computername cas001
$pools | %{$_.Recycle()}
$pools=Get-WMIObject IISApplicationPool -Namespace root\MicrosoftIISv2 -authentication Packetprivacy -computername cas002
$pools | %{$_.Recycle()}
Write-Host "Client Access IIS Application pools have been recycled."
Write-host ""
Write-host "Replicating the enterprise domain across sites..."
repadmin /syncall dc003.domain.com /APed
repadmin /kcc dc004.domain
repadmin /kcc dc003.domain
repadmin /kcc dc002.domain
repadmin /kcc dc01.domain
Write-Host "Replication requested, script complete."

Similar Messages

  • 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 change this script so it doesn't load into a new window?

    I have this script on an invisible button on a banner ad, but the client doesn't want the linked page to open in a new window, but rather load over the page in same window. How can I change the script to accomplish this, thanks!
    link_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    function mouseDownHandler(event:MouseEvent):void {
        navigateToURL(new URLRequest("http://www.sdesignsstore.com/store.html"));

    Try...
    navigateToURL(new URLRequest("http://www.sdesignsstore.com/store.html"), "_self");

  • How can I modify this script to return only certain rows of my mySQL table?

    Hi there,
    I have a php script that accesses a mySQL database and it was generated out of the Flex Builder wizard automatically. The script works great and there are no problems with it. It allows me to perform CRUD on a table by calling it from my Flex app. and it retrieves all the data and puts it into a nice MXML format.
    My question, currently when I call "findAll" to retrieve all the data in the table, well, it retrieves ALL the rows in the table. That's fine, but my table is starting to grow really large with thousands of rows.
    I want to modify this script so that I can pass a variable into it from Flex so that it only retrieves the rows that match the "$subscriber_id" variable that I pass. In this way the results are not the entire table's data, only the rows that match 'subscriber_id'.
    I know how to pass a variable from Flex into php and the code on the php side to pick it up would look like this:
    $subscriberID = $_POST['subscriberID'];
    Can anyone shed light as to the proper code modification in "findAll" which will take my $subscriberID variable and compare it to the 'subscriber_id' field and then only return those rows that match? I think it has something to do with lines 98 to 101.
    Any help is appreciated.
    <?php
    require_once(dirname(__FILE__) . "/2257safeDBconn.php");
    require_once(dirname(__FILE__) . "/functions.inc.php");
    require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
    * This is the main PHP file that process the HTTP parameters,
    * performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
    * and then serialize the response in an XML format.
    * XmlSerializer uses a PEAR xml parser to generate an xml response.
    * this takes a php array and generates an xml according to the following rules:
    * - the root tag name is called "response"
    * - if the current value is a hash, generate a tagname with the key value, recurse inside
    * - if the current value is an array, generated tags with the default value "row"
    * for example, we have the following array:
    * $arr = array(
    *      "data" => array(
    *           array("id_pol" => 1, "name_pol" => "name 1"),
    *           array("id_pol" => 2, "name_pol" => "name 2")
    *      "metadata" => array(
    *           "pageNum" => 1,
    *           "totalRows" => 345
    * we will get an xml of the following form
    * <?xml version="1.0" encoding="ISO-8859-1"?>
    * <response>
    *   <data>
    *     <row>
    *       <id_pol>1</id_pol>
    *       <name_pol>name 1</name_pol>
    *     </row>
    *     <row>
    *       <id_pol>2</id_pol>
    *       <name_pol>name 2</name_pol>
    *     </row>
    *   </data>
    *   <metadata>
    *     <totalRows>345</totalRows>
    *     <pageNum>1</pageNum>
    *   </metadata>
    * </response>
    * Please notice that the generated server side code does not have any
    * specific authentication mechanism in place.
    * The filter field. This is the only field that we will do filtering after.
    $filter_field = "subscriber_id";
    * we need to escape the value, so we need to know what it is
    * possible values: text, long, int, double, date, defined
    $filter_type = "text";
    * constructs and executes a sql select query against the selected database
    * can take the following parameters:
    * $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
    * $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
    * $_REQUEST["filter"] - the filter value
    * $_REQUEST["pageNum"] - the page index
    * $_REQUEST["pageSize"] - the page size (number of rows to return)
    * if neither pageNum and pageSize appear, we do a full select, no limit
    * returns : an array of the form
    * array (
    *           data => array(
    *                array('field1' => "value1", "field2" => "value2")
    *           metadata => array(
    *                "pageNum" => page_index,
    *                "totalRows" => number_of_rows
    function findAll() {
         global $conn, $filter_field, $filter_type;
          * the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
         $fields = array('id','subscriber_id','lastName','firstName','birthdate','gender');
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         $order = "";
         if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
              $order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //get the page number, and the page size
         $pageNum = (int)@$_REQUEST["pageNum"];
         $pageSize = (int)@$_REQUEST["pageSize"];
         //calculate the start row for the limit clause
         $start = $pageNum * $pageSize;
         //construct the query, using the where and order condition
         $query_recordset = "SELECT id,subscriber_id,lastName,firstName,birthdate,gender FROM `modelName` $where $order";
         //if we use pagination, add the limit clause
         if ($pageNum >= 0 && $pageSize > 0) {     
              $query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
         $recordset = mysql_query($query_recordset, $conn);
         //if we have rows in the table, loop through them and fill the array
         $toret = array();
         while ($row_recordset = mysql_fetch_assoc($recordset)) {
              array_push($toret, $row_recordset);
         //create the standard response structure
         $toret = array(
              "data" => $toret,
              "metadata" => array (
                   "totalRows" => $totalrows,
                   "pageNum" => $pageNum
         return $toret;
    * constructs and executes a sql count query against the selected database
    * can take the following parameters:
    * $_REQUEST["filter"] - the filter value
    * returns : an array of the form
    * array (
    *           data => number_of_rows,
    *           metadata => array()
    function rowCount() {
         global $conn, $filter_field, $filter_type;
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //create the standard response structure
         $toret = array(
              "data" => $totalrows,
              "metadata" => array()
         return $toret;

    Hi there,
    I have a php script that accesses a mySQL database and it was generated out of the Flex Builder wizard automatically. The script works great and there are no problems with it. It allows me to perform CRUD on a table by calling it from my Flex app. and it retrieves all the data and puts it into a nice MXML format.
    My question, currently when I call "findAll" to retrieve all the data in the table, well, it retrieves ALL the rows in the table. That's fine, but my table is starting to grow really large with thousands of rows.
    I want to modify this script so that I can pass a variable into it from Flex so that it only retrieves the rows that match the "$subscriber_id" variable that I pass. In this way the results are not the entire table's data, only the rows that match 'subscriber_id'.
    I know how to pass a variable from Flex into php and the code on the php side to pick it up would look like this:
    $subscriberID = $_POST['subscriberID'];
    Can anyone shed light as to the proper code modification in "findAll" which will take my $subscriberID variable and compare it to the 'subscriber_id' field and then only return those rows that match? I think it has something to do with lines 98 to 101.
    Any help is appreciated.
    <?php
    require_once(dirname(__FILE__) . "/2257safeDBconn.php");
    require_once(dirname(__FILE__) . "/functions.inc.php");
    require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
    * This is the main PHP file that process the HTTP parameters,
    * performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
    * and then serialize the response in an XML format.
    * XmlSerializer uses a PEAR xml parser to generate an xml response.
    * this takes a php array and generates an xml according to the following rules:
    * - the root tag name is called "response"
    * - if the current value is a hash, generate a tagname with the key value, recurse inside
    * - if the current value is an array, generated tags with the default value "row"
    * for example, we have the following array:
    * $arr = array(
    *      "data" => array(
    *           array("id_pol" => 1, "name_pol" => "name 1"),
    *           array("id_pol" => 2, "name_pol" => "name 2")
    *      "metadata" => array(
    *           "pageNum" => 1,
    *           "totalRows" => 345
    * we will get an xml of the following form
    * <?xml version="1.0" encoding="ISO-8859-1"?>
    * <response>
    *   <data>
    *     <row>
    *       <id_pol>1</id_pol>
    *       <name_pol>name 1</name_pol>
    *     </row>
    *     <row>
    *       <id_pol>2</id_pol>
    *       <name_pol>name 2</name_pol>
    *     </row>
    *   </data>
    *   <metadata>
    *     <totalRows>345</totalRows>
    *     <pageNum>1</pageNum>
    *   </metadata>
    * </response>
    * Please notice that the generated server side code does not have any
    * specific authentication mechanism in place.
    * The filter field. This is the only field that we will do filtering after.
    $filter_field = "subscriber_id";
    * we need to escape the value, so we need to know what it is
    * possible values: text, long, int, double, date, defined
    $filter_type = "text";
    * constructs and executes a sql select query against the selected database
    * can take the following parameters:
    * $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
    * $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
    * $_REQUEST["filter"] - the filter value
    * $_REQUEST["pageNum"] - the page index
    * $_REQUEST["pageSize"] - the page size (number of rows to return)
    * if neither pageNum and pageSize appear, we do a full select, no limit
    * returns : an array of the form
    * array (
    *           data => array(
    *                array('field1' => "value1", "field2" => "value2")
    *           metadata => array(
    *                "pageNum" => page_index,
    *                "totalRows" => number_of_rows
    function findAll() {
         global $conn, $filter_field, $filter_type;
          * the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
         $fields = array('id','subscriber_id','lastName','firstName','birthdate','gender');
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         $order = "";
         if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
              $order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //get the page number, and the page size
         $pageNum = (int)@$_REQUEST["pageNum"];
         $pageSize = (int)@$_REQUEST["pageSize"];
         //calculate the start row for the limit clause
         $start = $pageNum * $pageSize;
         //construct the query, using the where and order condition
         $query_recordset = "SELECT id,subscriber_id,lastName,firstName,birthdate,gender FROM `modelName` $where $order";
         //if we use pagination, add the limit clause
         if ($pageNum >= 0 && $pageSize > 0) {     
              $query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
         $recordset = mysql_query($query_recordset, $conn);
         //if we have rows in the table, loop through them and fill the array
         $toret = array();
         while ($row_recordset = mysql_fetch_assoc($recordset)) {
              array_push($toret, $row_recordset);
         //create the standard response structure
         $toret = array(
              "data" => $toret,
              "metadata" => array (
                   "totalRows" => $totalrows,
                   "pageNum" => $pageNum
         return $toret;
    * constructs and executes a sql count query against the selected database
    * can take the following parameters:
    * $_REQUEST["filter"] - the filter value
    * returns : an array of the form
    * array (
    *           data => number_of_rows,
    *           metadata => array()
    function rowCount() {
         global $conn, $filter_field, $filter_type;
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //create the standard response structure
         $toret = array(
              "data" => $totalrows,
              "metadata" => array()
         return $toret;

  • Firefox does not load the first time I click on it -- a script appears which ischrome://webvideodownloader/content/utils.js:131 -- when I stop this script running I can then load firefox -- how can I keep this script from running

    I can still load it with the script running or attempting to run in the background but it makes firefox tremendously slow. After I click on stop running the script then everything seems to be ok.
    how do I get the script not to run in the first place.

    In Firefox the use of the term chrome refers to the user interface and other elements that are not part of the web pages.
    See https://developer.mozilla.org/en/Chrome
    Your problems seems to be caused by the GreaseMonkey extension.<br />
    See [[Troubleshooting extensions and themes]]

  • How can i optimize this method

    protected String getTheRealKey(String currentLevel, String keyWithStar) {
    int starIndex = keyWithStar.indexOf("*");
    String keyInCollection;
    while (starIndex != -1) {
    keyInCollection = StringValue.first(currentLevel.substring(starIndex));
    keyWithStar = keyWithStar.substring(0, starIndex) + keyInCollection + keyWithStar.substring(starIndex+1);
    starIndex = keyWithStar.indexOf("*");
    return keyWithStar;
    }

    I do not see how you could optimize it further unless you wanted to use RegEx via String.replaceAll() in 1.4 and higher. However, it is rare that string manipulation will be your scaling bottleneck.
    - Saish

  • 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 can I optimize this CAN program?

    I currently have the program called "GCS message.vi". It reads CAN messages and has the ability to alter them. It then resends the CAN messages out. "GCS message stim and monitor.vi" runs with this, but does the opposite. It sends out messages, and then monitors the ouput of "GCS message.vi". This program runs at only a couple of Hertz, but when all the CAN programming is eliminated, the program runs extremely fast. And if all the excess programming is eliminated leaving only sending and receiving of CAN messages, then the program runs extremely fast again. I'm wondering what aspect of the program is slowing everything down and how I could program around it.
    Notes:
    The stim and monitor should be run first, and the start button on the VI should be pressed once the message vi is running.
    To check the execution speed, put a value in the "Inject Selected Errors" box and click the button next to it. It will countdown to zero.
    Attachments:
    GCS.zip ‏400 KB

    Hello,
    As you have noted, your problem seems to be purely LabVIEW. When you run with just your CAN commands, things are fast. One thing to note in your program (looking in CGS message.vi) is the large number of property node accesses; each access to a property node will cause a thread swap to the user interface (in the event that multiple threads have been spawned, which appears likely since you define multiple parallel tasks). Given that you have a relativel complicated GUI there, this may indeed affect performance significantly. In general, you should (if at all possible) use wires to dictate value assignment, and if necessary you may try changing the some of your property nodes (the ones that simply change the value of a control or indicator) to local variables to prevent the thread swapping. Now, this may not be the only performance enhancement to make; I would strongly recommend reading the following document to help get a better idea for how to find and correct memory and time performance issues in LabVIEW:
    http://zone.ni.com/devzone/conceptd.nsf/webmain/732CEC772AA4FBE586256A37005541D3
    Best Regards,
    JLS
    Best,
    JLS
    Sixclear

  • How can i optimize this querie

    Hi oracle developers i want this query gonna be faster than it is but i cant find the way. With functions the result was improved but not enough. Anybody can help me. Exist sometool that i can use.
    With explain Plan shows this:
    HASH Join
    Table Acces Full predetalle
    TableAcces Full funciones
    SELECT fun.fun_codigo                                   FUNCION
    ,fun.fun_desc FUNDESC
    ,SUM(NVL(pdt.pdt_disp,0)) DISPONIBLE
    ,SUM(NVL(pdt.pdt_apart,0)) APARTADO
    ,SUM(NVL(pdt.pdt_comp,0)) COMPROMETIDO
    ,SUM(NVL(pdt.pdt_real,0)) REAL
    ,SUM(NVL(pdt.pdt_presup,0)) PRESUPUESTADO
    ,SUM(pk_presupuestos.SumRealAcumuladoByFuncion(pdt.pdt_fun_codigo, pdt.pdt_per_anio, pdt.pdt_per_period, pdt.pdt_con_codigo)) REALACUM
    ,SUM(pk_presupuestos.SumPresAcumuladoByFuncion(pdt.pdt_fun_codigo, pdt.pdt_per_anio, pdt.pdt_per_period, pdt.pdt_con_codigo)) PRESUPACUM
    ,SUM(pk_presupuestos.SumRealAnualByFuncion(pdt.pdt_fun_codigo ,pdt.pdt_per_anio ,pdt.pdt_con_codigo)) REALANUAL
    ,SUM(pk_presupuestos.SumPresAnualByFuncion(pdt.pdt_fun_codigo ,pdt.pdt_per_anio ,pdt.pdt_con_codigo)) PRESUPANUAL
    ,fun.fun_tipo TIPO
    FROM FUNCIONES fun
         ,PREDETALLE pdt
    WHERE pdt.pdt_fun_codigo = fun.fun_codigo--fun.fun_codigo = pdt.pdt_fun_codigo
    AND pdt.pdt_per_anio = :anio
    AND pdt.pdt_per_period = :periodo
    AND pdt.pdt_vigente = 'V'
    AND ( :usuario IN (SELECT ful_empl_id FROM FUNNIVEL WHERE ful_fun_codigo = pdt.pdt_fun_codigo)
    OR :usuario IN (SELECT vep_empl_id FROM VERPRESUP WHERE vep_fun_codigo = pdt.pdt_fun_codigo)
    OR :usuario IN (SELECT fun_empl_resp FROM FUNCIONES WHERE fun_codigo = pdt.pdt_fun_codigo))
    GROUP BY fun.fun_codigo
    ,fun.fun_desc
    ,fun.fun_tipo;

    You might try replacing the multiple IN statements with
    AND :usuario IN (SELECT ful_empl_id
                       FROM FUNNIVEL
                       WHERE ful_fun_codigo = pdt.pdt_fun_codigo
                       UNION ALL
                       SELECT vep_empl_id
                       FROM VERPRESUP
                       WHERE vep_fun_codigo = pdt.pdt_fun_codigo
                       UNION ALL
                       SELECT fun_empl_resp
                       FROM FUNCIONES
                       WHERE fun_codigo = pdt.pdt_fun_codigo)TTFN
    John

  • Firefox 4 hangs while downloading files, sometimes get an error saying Script: chrome://mozapps/content/downloads/download.xml:68 is busy or may have stopped responding, how can I disable this script?

    While downloading files Firefox 4 freezes (started with 3.5) and sometimes I get a window that says Script: chrome://mozapps/content/downloads/download.xml:68 has stopped responding or is busy and asks if I want to stop script or ignore. I have looked through about:config and don't see a way to disable the script and keep it disabled.

    That is a problem with an AVG extension (Tools > Add-ons > Extensions)
    See:
    * [[Troubleshooting extensions and themes]]

  • How can i optimize this query

    SELECT c1,c2 FROM tabla WHERE c1=(SELECT MIN(c1) FROM tabla)
    (i want to get an unique register which contains the minimum value in the table for the field c1)

                                        C1                                     C2
                                         1                                     -1
                                         2                                     -2
                                         3                                     -3
                                         4                                     -4
                                         5                                     -5
                                         6                                     -6
                                         7                                     -7
                                         8                                     -8
                                         9                                     -9
                                        10                                    -10
    10 rijen zijn geselecteerd.
    SQL>
    SQL> SELECT c1,c2 FROM tabla WHERE c1=(SELECT MIN(c1) FROM tabla)
      2  /
                                        C1                                     C2
                                         1                                     -1
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE
       1    0   FILTER
       2    1     TABLE ACCESS (FULL) OF 'TABLA'
       3    1     SORT (AGGREGATE)
       4    3       TABLE ACCESS (FULL) OF 'TABLA'
    SQL>
    SQL> SELECT c1,c2
      2          FROM
      3                  (
      4                  SELECT c1,c2, ROW_NUMBER() OVER (ORDER BY C1) RN
      5                          FROM tabla
      6                  )
      7          WHERE RN = 1
      8  /
                                        C1                                     C2
                                         1                                     -1
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE
       1    0   VIEW
       2    1     WINDOW (SORT PUSHED RANK)
       3    2       TABLE ACCESS (FULL) OF 'TABLA'
    SQL>
    SQL> select min(c1) keep (dense_rank first order by c1) c1
      2       , min(c2) keep (dense_rank first order by c1) c2
      3    from tabla
      4  /
                                        C1                                     C2
                                         1                                     -1
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE
       1    0   SORT (AGGREGATE)
       2    1     TABLE ACCESS (FULL) OF 'TABLA'Regards,
    Rob.

  • How can i optimize this method,,,,,to increase its performance

    protected String getTheRealKey(String currentLevel, String keyWithStar) {
    int starIndex = keyWithStar.indexOf("*");
    String keyInCollection;
    while (starIndex != -1) {
    keyInCollection = StringValue.first(currentLevel.substring(starIndex));
    keyWithStar = keyWithStar.substring(0, starIndex) + keyInCollection + keyWithStar.substring(starIndex+1);
    starIndex = keyWithStar.indexOf("*");
    return keyWithStar;
    }

    STOP POSTING THIS MESSAGE YOU IDIOT!
    http://forum.java.sun.com/thread.jspa?threadID=653871&tstart=0

  • How can I get this script to produce a log of what is updated?

    spool h:\sql\Projects\BINLOOKP\BINLOOKP.log
    SET SERVEROUTPUT ON size 500000
    DECLARE
    v_schema     Varchar2(50);
    v_statement      Varchar2(500);
    CURSOR get_schemas IS
    SELECT DISTINCT t.owner
    FROM sys.dba_tables t
    WHERE t.table_name = 'BINLOOKUP'
    ORDER BY t.owner;
    BEGIN
    OPEN get_schemas;
    LOOP
    FETCH get_schemas INTO v_schema;
    EXIT WHEN get_schemas%NOTFOUND;
    v_statement := 'INSERT INTO '||v_schema||'.BINLOOKUP(BIN,HIERMAINTFLAG,CARDTYPE) SELECT T.BIN,T.HIERMAINTFLAG,T.CARDTYPE FROM TJELSMA.BINLOOKUP T WHERE T.BIN NOT IN (SELECT A.BIN FROM '||v_schema||'.BINLOOKUP A)';
    execute immediate v_statement;
    END LOOP;
    CLOSE get_schemas;
    END;
    /

    Did you want to know what you are inserting ?
    Try :
    SQL> set serveroutput on
    SQL> declare
      2   v_empno number;
      3   v_stmt  varchar2(4000);
      4  begin
      5   for i in (select empno from empb) loop
      6       v_stmt:='insert into empa values (:b1) returning empno into :b2';
      7       execute immediate v_stmt using i.empno returning into v_empno;
      8       dbms_output.put_line('Insert empno : '||v_empno);
      9   end loop;
    10  end;
    11  /
    Insert empno : 7369
    Insert empno : 7566
    Insert empno : 7788
    Insert empno : 7876
    Insert empno : 7902
    PL/SQL procedure successfully completed.Nicolas.

  • How can I optimize this query's performance

    SELECT pu.user_id,
    cd.owner,
    cd.somedata
    FROM client_detail cd,
    client_detail_user_xref pu
    WHERE cd.device_id = 'xxxxxxxxx'
    AND cd.client_detail_id = pu.client_detail_id(+)
    AND(cd.alt_user_id = '12345' OR pu.user_id = '67890')
    Plan hash value: 3532311591
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 247 | 1374 (1)| 00:00:17 |
    |* 1 | FILTER | | | | | |
    | 2 | NESTED LOOPS OUTER | | 1 | 247 | 1374 (1)| 00:00:17 |
    |* 3 | TABLE ACCESS FULL | CLIENT_DETAIL | 1 | 226 | 1371 (1)| 00:00:17 |
    | 4 | TABLE ACCESS BY INDEX ROWID| CLIENT_DETAIL_USER_XREF | 1 | 21 | 3 (0)| 00:00:01 |
    |* 5 | INDEX RANGE SCAN | CLIENT_DETAIL_USER_PK | 1 | | 2 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    1 - filter("CD"."ALT_USER_ID"='12345' OR "PU"."USER_ID"='67890')
    3 - filter("CD"."DEVICE_ID"='xxxxxxxxx')
    5 - access("CD"."CLIENT_DETAIL_ID"="PU"."CLIENT_DETAIL_ID"(+))
    Edited by: user13805875 on Feb 24, 2011 5:13 AM

    If you are posting a Performance Related Question. Please read
    {thread:id=501834} and {thread:id=863295}.
    Following those guide will be very helpful.

  • How best can i optimise this script

    I have a script the loops through a table and function. it works fine but it takes a longer time complete even though resources are given. the code below is just the same code i used how best can i represent it for speed even though i have all resources.
    For each_member in ( select from MemberTable where MemberID = 'ALL')*
    Loop
    Begin
    if Age >= 18 then
    hold:= 'Adult'
    end if;
    For Each_history in (select Acct,fx_function(each_member.ID,each_member.Acct) BR,
    Movement from History a where history_ID =each_member.Id)
    loop
    Begin
    insert into NewFilteredData (act,BR,mvt)
    values (Each_history.Acct,Each_history.BR,Each_history.Movement);
    end loop;
    end loop;
    end loop;
    commit;
    How best can i optimize this script to move data faster because they are a lot about 6000000 records to be moved.
    please help.
    Edited by: kama021 on Aug 25, 2009 12:48 PM
    Edited by: kama021 on Aug 25, 2009 12:48 PM

    Unless something is horribly wrong (i.e. the optimizer picks a radically incorrect plan), if you can do something in SQL, it will always be faster to do it in SQL. Doing things in PL/SQL, particularly using cursor FOR loops and single row inserts, is the slowest possible way to do anything (well, other than having nested FOR loops).
    Long before you start looking at things like the APPEND hint, I would focus on implementing a single SQL statement that generates the correct results. Once you have that and you have a benchmark, you can decide whether it is "fast enough". If it is (and I suspect it will be), you don't have to delve any deeper. If you need more performance, you can start looking into parallelism, the APPEND hint, etc. but be aware that this generally increases the complexity of the system.
    Justin

Maybe you are looking for

  • Is this a Virus??? Or What Is Going On???

    Also posted in Discussion Feedback since I could not find an actual Virus related group and the following refers to both a G3 and a G4. I realize that Apple, especially 10.4 is supposed to be immune to a virus but in the past two days I have run acro

  • Exception in implementing badi " hrpad00inftydb"

    Hi friends.. My need is to update infotype 0207 when ever employee changes address thru ess. I implemented the badi 'HRPAD00INFTYDB' and inside it called 'HR_MAINTAIN_MASTERDATA'. But its giving the following two exception : 1. Exception 'CX_HRPA_VIO

  • Create new LSMW using Idoc for HR master Data

    Hi Guys, I was wondering id someone could help me. I have started developing an LSMW, of which I have already created the Object. I have also created the Maintain attributes and I have supplied the Message Type, Basic Type and activated the IDOC inbo

  • 1Z0-108 Practice Study Material

    You can find that at http://www.beitcertified.com/oracle-1z0-108-exam-19953.htm

  • Installing photoshop onto a notebook

    I have Production Premium CS5.5 and from that, I want to install photoshop onto my notebook, which has no dvd or cd rom drive.  I copied the folder over, and had some wishful thinking, but to no avail, then looked for a setup.exe, also to no avail, c