Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

Query for getting last 6 month record

shid077
Tera Contributor

Query for getting last 6 month record from 'incident" table without using encoded query.

5 REPLIES 5

Pratiksha2
Mega Sage

Hello @shid077 
Please try below code: 

// Calculate the date 6 months ago
var sixMonthsAgo = new GlideDateTime();
sixMonthsAgo.addMonthsUTC(-6);

// Create a new GlideRecord object for the incident table
var gr = new GlideRecord('incident');
// Add a condition to filter records created within the last 6 months
gr.addQuery('sys_created_on', '>=', sixMonthsAgo);
// Execute the query
gr.query();
while (gr.next()) {
    // Do something with each incident record, for example:
    gs.info('Incident Number: ' + gr.getValue('number'));
}

Please Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,

Pratiksha

Harish KM
Kilo Patron
Kilo Patron

Hi @shid077 below example

var inc = new GlideRecord('incident');
inc.addQuery('sys_created_on','>',gs.monthsAgo(6)); // last 6 months
inc.query();
while(inc.next())
{
gs.info(inc.number);
gs.info(inc.getRowCount());
}

 

refer documentation

https://developer.servicenow.com/dev.do#!/reference/api/utah/server_legacy/c_GlideSystemAPI#r_GS-mon...

Regards
Harish

Mark Manders
Mega Patron

Why not use an encodedQuery? What are you trying to accomplish that you can't use it? Are you creating a report, doing an export, or something else?


Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

Abhijeet_Pawar
Tera Guru
Tera Guru

Hello @shid077 ,

Use below script which will resolve your issue.

var incidentGR = new GlideRecord('incident');
var sixMonthsAgo = new GlideDateTime();
sixMonthsAgo.addMonthsUTC(-6);
incidentGR.addQuery('sys_created_on', '>=', sixMonthsAgo);
incidentGR.query();
while (incidentGR.next()) {
    var incidentNumber = incidentGR.getValue('number');
    var shortDescription = incidentGR.getValue('short_description');
    
gs.info('Incident Number: ' + incidentNumber +"\n"+'Short Description:'+shortDescription);
}
 

If my response helps you resolve your issue. Kindly mark it as helpful & correct. It will be helpful to future readers! 

Thanks and Regards,
Abhijeet Pawar.