Background scripts for Deletion

Jyoti36
Mega Expert

Hi,

I need to write background script to delete some unwanted data from multiple tables. I am just concerned about following the best approach like performing deletions from Master table and then the child tables. I am thinking to write a scheduled job or may be an on-demand script for the same.
Can anyone please share some scripts or guide on how can I handle the data correctly as this will involve multiple table records.

Regards
Jyo

1 ACCEPTED SOLUTION

Hi Jyo,



For multiple tables, just wrap your deletion script in a loop. Something like this. WARNING: UNTESTED CODE AHEAD!



(function () {


      var tableList = ['cmdb_ci', 'task', 'cmn_location', 'cmn_department' ];


      for (var i = 0; i < tableList.length; i++) {


                  var gr = new GlideRecord(tableName[i]);


                  gr.query();


                  gr.deleteMultiple()


      }


})();



As far as base tables and extended tables... deleting records on a base table (like cmdb_ci or task) deletes all child records as well - just tested.)


View solution in original post

16 REPLIES 16

Your encoded query string is going to need quotes...



gr.addEncodedQuery('u_owner=abf6b5030f5d9699f5a07f5ce1050eda^sys_created_by!=Jyo');



AND - this is important - if the table you are using doesn't have a u_owner field, this query is ignored and all your records will be deleted (because you effectively have no filter.)


Had to learn that one the hard way.


I think we all did. There is a property and a gs.getSession() setting that can enforce it. Why the property is not TRUE by default is anyone's guess.


Yea that's right... so potentially I will include the tables which have relevant fields as per my query.. so what I am doing is I have multiple tables where in I will be using the same query and there are other set of tables which use some other similar query, so for those I am gonna write another script.


So will write different set of scripts but eventually with your suggested script my work will be less as most of the table will be around some similar queries.


Thanks for your quick response and help. I will try the solution first then apply it to massive data, as deletions are always very sensitive.


Have a good one!



Regards


Jyo


Just one last thing, can I use the same functionality in the fix scripts as well.



Regards


Jyo