- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 02:05 PM
I've been a developer for 8+ years, and apparently I missed this in ServiceNow 101.
Am I going crazy? why do I get the last nds_code when I'm just capturing the nds_code if number = G280002292
var ndsCode = '';
var gr = new GlideRecord(<tablename>);
gr.addEncodedQuery('lookup_client_last_name=PATRICK');
gr.query();
while(gr.next()){
if(gr.number == 'G280002292'){
ndsCode= gr.nds_code;
gs.info(ndsCode); //correct data
}
}
gs.info(ndsCode); //captures data on the last record
I get the correct ndsCode captured within the IF statement but then out of the statement I getting the last ndscode
It's setting ndsCode variable whether number is G280002292 or not.
Is this as designed?
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-06-2024 02:46 PM - edited 10-06-2024 03:27 PM
If the field you are assigning to the variable is not a string, you are storing the object memory location. Since you are not exiting the while loop after the record is found and the script variable updated, it's using the value of the last record retrieved. You can force the retrieved to a field, or the safer/surer way if getting the value like this:
ndsCode = gr.nds_code.toString();
-or-
ndsCode = gr.getValue('nds_code');
If you are using a script like this beyond a demonstration of the issue, it would be more efficient if you added the number field and value to the query/encoded query before retrieving records, and/or breaking out of the while loop when the record is found.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-07-2024 12:35 AM
Hi @kemmy1 ,
I tried your problem in my PDI please refer to below script
var ndsCode = '';
var gr = new GlideRecord('incident');
gr.addEncodedQuery('active=true^caller_id=681ccaf9c0a8016400b98a06818d57c7');
gr.query();
while (gr.next()) {
if (gr.number == 'INC0000007') {
ndsCode = gr.getValue("short_description");
gs.info("Here = " + ndsCode); //correct data
}
}
gs.info("Outside " + ndsCode); //captures data on the last record
By writing ndsCode = gr.getValue("short_description"); this will store the string value of ndsCode to your variable
Please mark my answer correct and helpful if this works for you
Thanks and Regards
Sarthak