How can I optimize my Script Include to insert or update a row in a table?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-30-2018 03:13 PM
I have a Script Include that has code to insert or update a custom table with values from 3 SN tables when the record is either updated or inserted. My custom table has over 50 columns and it's become messy because I repeat the same statements at least twice for each of the SN tables. I would like to call a function that copies the fields from one table to another and only have to type (or read) them once. I did try putting them into a function but it didn't work, the data was not inserted or updated. Can anyone give me some suggestions on how to solve this problem?
A code sample:
updateCustomTable: function(/*GlideRecord*/project) {
var sysId = project.getValue('sys_id');
// check to see if a row already exists
var custom = new GlideRecord('u_customtable');
custom.addQuery('u_project', sysId);
custom.query();
if(custom.getRowCount() > 0) {
while(custom.next()) {
custom.setValue('field1', project.getvalue('field1');
custom.setValue('field2', project.getValue('field2');
etc. for 50 more fields
custom.update();
}
}
else {
custom.initialize();
custom.setValue('field1', project.getvalue('field1');
custom.setValue('field2', project.getValue('field2');
etc. for 50 more fields
custom.insert();
}
},

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-09-2018 11:39 PM
Hi gjz,
The code below allows to copy all table's fields without listing its names:
updateCustomTable: function(/*GlideRecord*/project) {
var sysId = project.getValue('sys_id');
// check to see if a row already exists
var custom = new GlideRecord('u_customtable');
custom.addQuery('u_project', sysId);
custom.query();
if(custom.getRowCount() > 0) {
while(custom.next()) {
custom = this._initializeGR(custom, project);
custom.update();
}
} else {
custom.initialize();
custom = this._initializeGR(custom, project);
custom.insert();
}
},
_initializeGR: function(/*GlideRecord*/custom, /*GlideRecord*/project) {
var fields = project.getFields();
for (var i = 0; i < fields.size(); i ++) {
/* don't copy the sys_id*/
if (fields.get(i).getName() != 'sys_id') { // extend it if you need to skip more fields
custom.setValue(fields.get(i).getName(), project.getValue(fields.get(i).getName()));
}
}
return custom;
},