Friday, March 15, 2013

Quick Opportunity Change Owner Script

As sales people come and go I am often asked to change opportunity ownership status using a variety of criteria. Often I could do the change with the Salesforce UI but a find running a simple SQLForce a lot quicker (and way more adaptable).

I have used the following core script for years -- all I have to do modify the "sqlWHERE" definition in the code when a new situation arises.  Believe me, typing "jython

import SQLForce

def _getOwnerId( session, alias ):
    return"select id from user where alias='" + alias + "'")[0][0];
if __name__ == '__main__':
    session = SQLForce.Session("production")
    newOwnerAlias = "newSalesperson"
    oldOwnerAlias = 'oldSalesperson"

    newOwnerId = _getOwnerId( session, newOwnerAlias )

    sqlWHERE = "owner.alias='" + oldOwnerAlias + """'
                AND isClosed=false
                AND closeDate >= 2012-01-01
    updateRecords = []
    for record in session.selectRecords( "SELECT id from Opportunity WHERE " + sqlWHERE ):
        updateRecords.append( [, newOwnerId ])

    if len(updateRecords) > 0:
        print "Time to Update ", len(updateRecords)
        session.update( "Opportunity", ["ownerId"], updateRecords )
print "No records modified"

Note: SQLForce is freeware at

No comments: