I want to insert a record if a condition is met

hamidouche
Kilo Expert

Hi,

I am importing some data and inserting them as rows in a table. I first query the table to see if a record already exists. If it does, then I will only update one of its fields, called 'statut', otherwise I will insert all new records (4 fields)

The problem is that I do update the existing record, but it inserts it also as a new record, so there's a duplicate record. As you can see, I also do a GlideRecord twice on the same table, which I feel a bit redundant and maybe even inefficient. Here is my code:

var recordDemande = new GlideRecord('table_name');
recordDemande.initialize();

//check if the record exists: do I need to GlideRecord the table again?
var checkRecord = new GlideRecord('same_table as above');
checkRecord .addEncodedQuery('u_codeLIKEA10012' + code);
checkRecord .query();
if(checkRecord .next()){
     checkRecord .setValue('u_statut', statut);
}else{
recordDemande.setValue("u_nom", nom);
recordDemande.setValue("u_prenom", prenom);
recordDemande.setValue("u_code", code);
recordDemande.setValue("u_active", statut);
				
			}
			
			
recordDemande.update();

1 ACCEPTED SOLUTION

Suseela Peddise
Kilo Sage

Hi,

Try the below code:

var checkRecord = new GlideRecord('<<table>>');

checkRecord .addEncodedQuery('u_codeLIKEA10012' + code);

checkRecord .query();

if(checkRecord .next()){ //if it is exists update the value

checkRecord .setValue('u_statut', statut);

checkRecord.update();

}

else{ //if not create a new Record

checkRecord.initialize();

checkRecord.setValue("u_nom", nom);

checkRecord .setValue("u_prenom", prenom);

....

checkRecord.insert();

 

}

 

If I have answered your question, please mark my response as correct and/or helpful.

Thanks,

Suseela P.

 

View solution in original post

10 REPLIES 10

Unfortunately, it's not working. Specifically, it's not updating the existing record or if there it's duplicating the same record again

Swadesh Saraf2
Kilo Guru

just wondering why aren't you using transform maps for this? It is there to make life easy 🙂

It's not relevant for this. But to answer your question, import sets is too much machinery for a once-in-a month import

Ok, so basically to fix this issue here you go:

 

//check if the record exists: do I need to GlideRecord the table again?
var checkRecord = new GlideRecord('same_table as above');
checkRecord.addEncodedQuery('u_codeLIKEA10012' + code);
checkRecord.query();
if(checkRecord.next()){
     checkRecord.u_statut=statut;
     checkRecord.update();
}else{
checkRecord.initialize();
checkRecord.u_nom= nom;
checkRecord.u_prenom=prenom;
checkRecord.u_code=code;
checkRecord.u_active=statut;
checkRecord.insert();				
}

 

I hope this helps 🙂

The code detects correctly the existing record (I put a gs.info() inside the if branch), but it's not updating it though