---
sourceDocument: Brazil Customer Service Management
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/customer-service-management

 Release :

    - brazil

ft:locale :

    - en-US

ft:publication_title :

    - Brazil Customer Service Management

ft:clusterId :

    - csm

bundleId :

    - csm

workflow :

    - Customer and Industry


---

# Example script that queries the Opportunity table

# Example script that queries the Opportunity table {#csm-opportunity-table-script___Ref16694770}

Release version: Brazil  
Updated September 10, 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 2 minutes to read
Summarize  
![AI sparkle icon](https://servicenow.com/docs/portal-asset/ai-sparkle-icon) Summarized using AI  
This content was generated using new OpenAI-powered functionality. Results are provided on an as is basis and are not guaranteed to be accurate or complete.  

## Summary of Example script that queries the Opportunity table

This example script demonstrates how to query the Salesforce Opportunity table using three custom actions within a ServiceNow integration:Get All Opportunities,Get Opportunities for Account Id, andGet Opportunity Details.
It guides you through selecting the appropriate action based on input parameters, executing the call, and processing the resulting data to populate a remote table in ServiceNow.
Show full answer Show less  

## Key Features

* **Dynamic action selection:** The script chooses which custom action to invoke depending on the parameters passed in the query, allowing flexible retrieval of all opportunities, opportunities for a specific Salesforce account, or details of a specific opportunity.
* **Input validation and messaging:** If a Salesforce account ID is required but undefined, the script displays an informative message and aborts the action call to prevent unnecessary queries.
* **Action execution:** The selected Salesforce spoke action is called via `snfd.FlowAPI.executeAction`, passing the prepared inputs and receiving outputs including opportunity data or error messages.
* **Error handling:** The script checks the action status and throws errors for unsuccessful calls, which are caught and logged with user-friendly error messages.
* **Data mapping:** Retrieved Salesforce Opportunity fields (Amount, CloseDate, Name, Probability, AccountId, StageName, Type, Id) are mapped into corresponding columns in the remote table, with the Salesforce record ID assigned as the `sysid` to maintain synchronization.
* **Information messages:** Any informational messages returned by the Salesforce query are displayed to the user, enhancing transparency.

## Practical Application for ServiceNow Customers

This script enables ServiceNow customers to seamlessly integrate and synchronize Opportunity data from Salesforce into their ServiceNow environment. By using this approach, customers can:

* Retrieve and display comprehensive Opportunity data dynamically based on user input or context.
* Maintain accurate record identification through consistent use of Salesforce record IDs as `sysid` in the remote table, ensuring reliable data updates and lookups.
* Implement robust error and edge case handling to improve reliability and user experience.
* Extend or customize the script to fit specific business needs by modifying input parameters or processing logic.

Overall, this script provides a practical, reusable pattern for integrating Salesforce Opportunity data into ServiceNow, enabling enhanced visibility and management of sales opportunities directly within the ServiceNow platform.  
This example script queries the opportunity table using the Get All Opportunities, Get Opportunities for Account Id, and
Get Opportunity Details custom actions.  
The example script consists of three distinct parts:

1. The first part selects the correct custom action and prepares inputs for it.
2. The second part makes a call to the action.
3. The third part processes the outputs of the action.
{#csm-opportunity-table-script__ol_u1s_tyj_v3b}

## Selecting a spoke action and preparing the inputs {#csm-opportunity-table-script__section_select_spoke_actions}

In this section of the script, select one of the three custom actions that you are prepared to get opportunities from the Salesforce application:

* Get All Opportunities
* Get Opportunities for Account Id
* Get Opportunity Details

{#csm-opportunity-table-script__ul_z1q_bzj_v3b} You can decide which action to call based on the parameters included in the `v_query` function argument.  

    /****** Choose action and prepare action inputs *****/
    var action = null;
    var inputs = {};

    // look up opportunity by salesforce record id
    if (v_query.isGet()) {

      action = "get_opportunity_details";
      inputs.salesforce_opportunity_record_id = v_query.getSysId();
          

    // look up opportunities by salesforce account id
    } else if (v_query.getParameter("u_sf_account_id")) {

        if (v_query.getParameter("u_sf_account_id") == "undefined") {
          gs.addInfoMessage("Opportunities cannot be retrieved because " +
                            "this "Account does not have associated "    +
                            "Salesforce Account. Please contact System " +
                             "Administrator.");
          return;

        } else {
          action = "get_opportunities_for_account_id";
          inputs.salesforce_account_id = v_query.getParameter("u_sf_account_id");
        }

    // look up all opportunities
    } else {
      action = "get_all_opportunities";
    }

Note that this script configures an information message if the Salesforce account is undefined when it's required by the action. The undefined value comes from the relationship that is described in [Using a related list to create the connection between the Customer Account and the Salesforce Opportunities](https://servicenow-prod.fluidtopics.net/9q6pyLnIyfBdar0Yq74wfQ "Use a related list to link the Customer Account table with Salesforce Account Id, and the Salesforce Opportunity remote table with the same Account Id.").

When the Salesforce account is undefined, there's nothing to query for in this case and the function returns without calling the spoke action.

## Calling the spoke action {#csm-opportunity-table-script__section_ed2_pzj_v3b}

In this section of the script, call the action using the names of the Salesforce
spoke and the selected action and store the outputs of the call.  

    /***** Call action *****/
    var outputs =
            sn_fd.FlowAPI.executeAction("sn_salesforce_spok." + action, inputs);

## Processing the action output {#csm-opportunity-table-script__section_pqr_szj_v3b}

In this section of the script, process the outputs starting with the check for
errors.  

    /***** Process action outputs *****/
    if (outputs.status != "Success") {
    throw new Error(outputs.error_message);
    }

If the query doesn't return any errors, the script must process the returned records and add them as rows into the remote table. Map the Salesforce Opportunity fields into the remote table columns.  

    var opportunities = outputs.opportunities.data;

     for (var i = 0; i < opportunities.length; i++) {
      var opportunity = opportunities[i];
      v_table.addRow({
        "u_sf_amount": opportunity.Amount,
        "u_sf_close_date": opportunity.CloseDate,
        "u_sf_name": opportunity.Name,
        "u_sf_probability": opportunity.Probability + "%",
        "u_sf_account_id": opportunity.AccountId,
        "u_sf_stage": opportunity.StageName,
        "u_sf_type": opportunity.Type,
        "sys_id": opportunity.Id,
      });
    }

Note that the Salesforce opportunity record Id is assigned to the remote table sys_id. This verifies that lists and forms for the remote table function properly and that we are able to extract the record Id using
`v_query.getSysId()` the next time that the remote table script is invoked.

Then display the information message if it was passed by the query.  

    if (outputs.info_message) {
      gs.addInfoMessage(outputs.info_message);
    }

## Putting the remote table script sections together {#csm-opportunity-table-script__section_z11_k1k_v3b}

The three sections of the script are included in the try-catch block to provide for
error handling.  

    (function executeQuery(v_table, v_query) {

      try {

        // place code here from: <Selecting a spoke action and preparing the inputs>

        // place code here from: <Calling the spoke action>

        // place code here from: <Processing the action output>  	
            
      } catch (error) {
        gs.addErrorMessage("Error retrieving  Salesforce Opportunities. " +
                           "Please contact System Administrator.");
        gs.addErrorMessage("System Error: " + error.message);
      }

    })(v_table, v_query);


