How to combine two queries into one result set without encoded query.

Stephen W_
Giga Guru

Pretty basic question I think.. but I'm drawing a blank:

u_somefield=NULL^request_lineISNOTEMPTY^NQu_anotherfield=9697d9046f3a3100f24ced250d3ee40f

Encoded queries are not fun for maintenance, so I try to stick to "addQuery()" type functions.

The above query is really two queries, or a single query with a level of nesting.

u_somefield=NULL^request_lineISNOTEMPTY

+

u_anotherfield=9697d9046f3a3100f24ced250d3ee40f

How can I write this using standard addQuery/addNull.. etc with the appropriate nesting?

Thanks!

1 ACCEPTED SOLUTION

This might be a bit simpler.



var gr = new GlideRecord('table');


gr.addQuery('u_somefield', NULL);


gr.addQuery('request_line', '!=', NULL);


var queryTwo = new GlideRecord('table');


queryTwo.addQuery('u_anotherfield', '9697d9046f3a3100f24ced250d3ee40f');


gr.addEncodedQuery("^NQ" + queryTwo.getEncodedQuery());


gr.query();


while(gr.next()){


//Process


}



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

View solution in original post

16 REPLIES 16

Chris H2
Giga Guru

Hi Steve (and others facing the same issue),

Agreed writing a long old addEncodedQuery is a bit rubbish for maintainability, but there doesn't seem to be an standard GlideRecord method for it. I got round this by building a single encoded query line-by-line:

var qry = 'u_strfieldLIKEtest'; // Declare string, and first condition
qry += '^ORu_strfieldLIKEsomethingelse'; // Add simple OR condition
qry += '^u_boolfield=true'; // Add AND condition
qry += '^NQu_numfield=7'; // Add new query aka 'big OR'
gr.addQuery(qry); // (addQuery with 1 parameter is now identical to addEncodedQuery)w

When building strings like this, you have to be careful with ordering. For more complex queries it may make sense to declare arrays then .join() them with ^, ^OR or ^NQ as appropriate.

Hope this helps,

Chris

Just wanted to update my response to this question - if I faced the same issue I would be tempted to use GlideQuery, which does this natively in its orWhere condition builder.

Peter Bell explains it best in his blog post "GlideQuery - Complex Queries":
https://developer.servicenow.com/blog.do?p=/post/glidequery-p8/