Service Now - Find a Record in an Unknown Table by sys_id

Thursday Apr 9, 2020

If you have a sys_id, say it was returned from calling a poorly documented function (in ServiceNow??? Never!!!).

You can use this sript to search for it, but be aware it could take a very long time - on an instance cloned from a decent sized production instance it took 2.4 hours.

Basically, we want to look at the sys_db_object table and search every data table for that sys_id.

If we know the table is a test table, we can try adding someething like x.addQuery('name', 'CONTAINS', 'test'); to narrow our search down.

Code

Here’s the code:

     var searchSys_id = "dec6b6181b021850d974edf9bc4bcbdb";
     
     var x = new GlideRecord('sys_db_object'); //sys_db_object - table contains all tables that contain data
     
     x.addActiveQuery();
     // x.addQuery('name', 'CONTAINS', 'test');
     x.addQuery();
     x.query();
     var count = 0;
     while(x.next()) {
            try {
              gs.debug("Searching : " + x.name);
                    var y = new GlideRecord(x.name);
                    y.addQuery('sys_id',searchSys_id);
                    y.addActiveQuery();
                    y.query();
                    while(y.next()) {
                            if(y.sys_id == searchSys_id ) // NEED this double check or else log will spit out alot lot of rubbish {
                                    gs.log(" ID: " + y.sys_id + " Table Name: " + x.name + " Name: " + y.name + " Class: " + y.sys_class_name);
                                    gs.log(y.getRowCount());
                            }
                    } 
            }
            catch(e) {
                gs.log("ID ERROR: " + e); 
            }
     }