ServiceNow insert() inside of gr.next()

I ran into a problem recently when trying to run a fix script with my then-boss.

It’s been a couple of weeks now, but to the best of my memory, we had queried the database for a list of records, and then were wanting to insert into another table using one or more pieces of data from the list of records.

It seems like an easy problem to solve.

var gr = new GlideRecord(‘table_name’)

Then add your query parameters and run gr.query()

Finally, you then use while(gr.next()){} to step through the records, and inside of your while loop, you create a new GlideRecord object that you can use to insert the new record.

However, after several iterations, we weren’t able to get the insert to work while it was nested inside of the while loop.

My workaround for that is to step through the records using the gr.nex(), and push the information I need from the records onto an array (or an array of objects). Then, further down I can step through the array and do whatever inserting I need to. That worked without problem, and more closely mirrored what I do with function calls (since you can only return one item, if I want to return anything complex I end up placing the information I need into an array, an object, or an array of objects, and then just returning that).

Hopefully that will save some of you fifteen minutes at some point when you avoid replicating the problems we had.

Leave a Reply