We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

avoid repeated code for multiple gliderecord

Not applicable

Hello Team,

 

Some times in a code we have do multiple glideRecord in a script. Below code fuction will help you to avoid multiple glideRecord. Here you can pass field & value  as initializeFields object. This code will check if a record is present on the table if not it will create and return the sysid.

// Helper function to retrieve or create a record in a table
    function getOrCreateRecord(tableName, queryField, queryValue, initializeFields) {
        var gr = new GlideRecord(tableName);
        gr.addQuery(queryField, queryValue);
        gr.query();
        if (!gr.next()) {
            gs.info("Subham: No record found in " + tableName + " for " + queryValue);
            gr.initialize();
            for (var field in initializeFields) {
                gr[field] = initializeFields[field];
            }
            gr.insert();
        } else {
            gs.info("Subham: Record found in " + tableName + " with sys_id = " + gr.sys_id);
        }
        return gr.sys_id;
    }
 
Thanks
0 REPLIES 0