Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

GlideRecord Query Question

Mussie
ServiceNow Employee
ServiceNow Employee

Hi Guys,

I have a user reference field in one of the custom tables I created and this field should only fetch users who have Roles A and B (both).

I am querying sys_user_has_role table but having difficult in fetching the values without writing two queries. I can easily do this if I write two queries using below but this is a bit slow and I was hoping to do this in one query. Any ideas?

Here is what my query looks like at the moment:

getRoleAB: function() {

        var roleA = [];

        var roleB = [];

        var roleAGR = new GlideRecord ('sys_user_has_role');

        roleAGR.addQuery('role', '2010067c4fce0300592d52411310c78d');

        roleAGR.query();

        while (roleAGR.next()){

                  roleA.push(roleAGR.getElement('user').toString());

        }

        var roleBGR = new GlideRecord ('sys_user_has_role');

        roleBGR.addQuery('role', 'fadf397c4fce0300592d52411310c7ac');

        roleBGR.addQuery('user', 'IN', roleA);

        roleBGR.query();

        while (roleBGR.next()){

                  roleB.push(roleBGR.getElement('user').toString());

        }

        return roleBGR;

},

Thank you,

Mussie

27 REPLIES 27

Gurpreet07
Mega Sage

Below should workfine



  1. getRoleAB: function() {  
  2.         var roleA = [];  
  3.         var roleB = [];  
  4.         var roleAGR = new GlideRecord ('sys_user_has_role');  
  5.         roleAGR.addQuery('role', '2010067c4fce0300592d52411310c78d').addOrCondition('role', 'fadf397c4fce0300592d52411310c7ac'); ;  
  6.         roleAGR.query();  
  7.         while (roleAGR.next()){  
  8.                   roleA.push(roleAGR.getElement('user').toString());  
  9.         }  
  10.         return roleBGR;  
  11. },

Mussie
ServiceNow Employee
ServiceNow Employee

Hi Gurpreet, thanks for the reply. I am not looking for or condition, the user should have both those roles.


Mussie


Then simply user one more addQuery(). Also user ArrayUtil for unique values.



  1. getRoleAB: function() {
  2.         var roleA = [];
  3.         var roleB = [];
  4.         var roleAGR = new GlideRecord ('sys_user_has_role');
  5.         roleAGR.addQuery('role', '2010067c4fce0300592d52411310c78d')
    1. roleAGR.addQuery('role', 'fadf397c4fce0300592d52411310c7ac');
  6.         roleAGR.query();
  7.         while (roleAGR.next()){
  8.                   roleA.push(roleAGR.getElement('user').toString());
  9.         }
  10.         return roleBGR;
  11. },

Mussie
ServiceNow Employee
ServiceNow Employee

Already tried that, this wouldn't work as a user can't have role A and B in one record.