Issue deleting records directly from a set of queried records.

HugoFirst
Kilo Sage

I use a web based AI to review my code and I was surprised by one of the issues identified. It has to do with a script that queries a table and deletes the resulting records.   


My code follows this pattern:

var gr – GlideRecord(‘table’);

gr.addEncodedQuery(‘a=b’);
gr.query();

while ( gr.next() )

   {

   Gr.deleteRecord();

   }

 

 

The AI chat said that there is a well known issue with this logic and that I could miss a record in the results set since I’m deleting them along the way.  It recommends that I save the sys_id’s of the records in an array and then iterate over the array to delete the records.

Something like this:

var sys_ids = [];

var gr – GlideRecord(‘table’);

gr.addEncodedQuery(‘a=b’);
gr.query();

while ( gr.next() )

   {

  sys_ids.push(gr.sys_id);

   }

 

for ( var I = 0; I < sys_ids.length; i++ )

   {

  var delGR = GlideRecord(‘table’);

  if ( ! delGR.get(sys_ids[i] ) )

     {

     delGR.deleteRecord();

     }

}

 



My question is this:  Is there really an issue with deleting records directly from a set of queried records?
Should I follow AI's advice?

0 REPLIES 0