addEncodedQuery is ignored

thomaskennedy
Tera Guru

I have a function to track down references to a particular sys_id in various tables:

_getTableReferences: function(refTable, sysId) { }

The refTable param is like so:

{
  "table": "incident",
  "column": "location",
  "condition": "sys_created_on>=javascript:gs.beginningOfLast12Months()"
 }

I want all rows from refTable.table where refTable.column (this is always a Reference column) equals sysId, unless refTable.condition exists, in which case I want only rows also matching that condition. So this is what I wrote:

var gr = new GlideRecord(refTable.table);
gr.addQuery(refTable.column, sysId);
if(refTable.condition) gr.addEncodedQuery(refTable.condition);
gr.query();
while (gr.next()) {...}

But I find that although the condition gets added, it does not filter the results. To use my example above, incidents are included regardless of their created date.

So I tried adding the encoded query first:

var gr = new GlideRecord(refTable.table);

if(refTable.condition) {
  gr.addEncodedQuery(refTable.condition);
}
			
gr.addQuery(refTable.column, sysId);
gr.query();
while (gr.next()) {...}

But that made no difference. I've seen many posts on this general subject, but they all involve an encoded query that contains a complex condition or an OR, which mine does not. What's going on here?

 

 

 

6 REPLIES 6

jaheerhattiwale
Mega Sage
Mega Sage

@thomaskennedy If condition is present then you want the rows also matching that condition means you need OR condition between then not AND. So the code should be as follows:

var gr = new GlideRecord(refTable.table);

var columnCondition = gr.addQuery(refTable.column, sysId); //This will be always added

if(refTable.condition) {
  columnCondition.addOrCondition(refTable.condition); //If condition is present then we will show the results matching that too
}
gr.query();
while (gr.next()) {...}

 

Please mark as correct answer if this solves your issue.

Please mark the answer as correct or helpful based on impact
ServiceNow Community Rising Star, Class of 2023

@jaheerhattiwale The filter is there to screen out rows I do not want to bother updating, for example old incidents. This is why I use the AND. However, it does no harm if those rows get updated also, so if I do not get this figured out I will just leave it.