Copy fields from one table to another

tanz
Tera Expert

I have to tables A and B. A has fields a,b,c,d.....,z (26 fields) and B also has same number of fields with same name a,b,c,d.....,z (26 fields). Whenever an record is inserted in table A via a background script or some other backend process, the same should be copied to table B by automatically checking the field name it should map.

 

Can you please help on the script.

 

4 REPLIES 4

Ankur Bawiskar
Tera Patron
Tera Patron

@tanz 

it should be an easy task.

you can use after insert BR on Table A OR you can also use flow designer for this

what did you start with and where are you stuck?

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi,

I was trying to do this via a BG script but I want to avoid trying to copy all the fields line by line as there are too many fields. Is there any way to copy directly from one record to another as the backend names are same

var gr = new GlideRecord('A');
        gr.orderByDesc("sys_created_on");
        gr.query();
        while (gr.next()) {
            var gr1 = new GlideRecord('B');
            gr1.initialize();
            gr1.u_a = gr.u_a;
            gr1.u_b = gr.u_b;
 
            gr1.insert();
        }

@tanz 

something like this

	try{
		var gr = new GlideRecord("tableA");
		gr.query();
		while (gr.next()) {

			var tableAFields = ['field1','field2','field3']; // give here the 26 fields from table A
			var tableBFields = ['field4','field5','field6']; // give here the 26 fields from table B

			// ensure you keep sequence of the fields correctly i.e. field1 from table A to be mapped with field4 from table B and so on

			var rec = new GlideRecord('tableB');
			rec.initialize();

			for(var i in tableAFields)
				rec[tableBFields[i]] = gr[tableAFields[i]];

			rec.insert();
		}
	}
	catch(ex){
		gs.info(ex);
	}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

newhand
Mega Sage

@tanz 
GlideRecord has a function named   getElements()。
You can use this funtion to get all the field elements, and then you can get the field name from each element without any hardcoding.

sample code

var userRec = new GlideRecord("sys_user"); // GlideRecord to sys_user table

userRec.get("5137153cc611227c000bbd1bd8cd2005"); // Sys Id of user: Fred Luddy

var fields = userRec.getFields();

for (var i = 0; i < fields.size(); i++) {

    var field = fields.get(i);
    var name = field.getName(); // Name of the field
    var label = field.getLabel(); // Label of the field
    var value = field.getDisplayValue(); // Value of the field

    gs.info((Number(i) + 1) + ".\n" + "Field Label: " + label + "\n" + "Field Name: " + name + "\n" + "Field Value: " + value);

};




 

Please mark my answer as correct and helpful based on Impact.