I have a function in my Node app, that makes use of the mssql
package, to run some SQL updates. What I want to be able to do is pass in a variable for the actual update query/value, so that I can re-use the function. But I'm running into a problem where the value I'm passing in is undefined
because of the scope.
To be clear, it will work if I do this:
if (recordsToUpdate.length > 0 && sourceRecords.length > 0) {
for (let record of recordsToUpdate) {
for (let source of sourceRecords) {
if (record.NoteDetailsId === source.notes_detail_id) {
console.log('source.category: ', source.category);
const updateQuery = `
UPDATE Emp_Worksheets
SET Category = '${source.category}';
`;
await sqlServerQueryHandler(updateQuery);
}
}
}
}
But if I move the updateQuery
outside the function I get a 'source' is not defined error:
let updateQuery = `
UPDATE Emp_Worksheets
SET Category = '${source.category}';
`;
if (recordsToUpdate.length > 0 && sourceRecords.length > 0) {
for (let record of recordsToUpdate) {
for (let source of sourceRecords) {
if (record.NoteDetailsId === source.notes_detail_id) {
console.log('source.category: ', source.category);
await sqlServerQueryHandler(updateQuery);
}
}
}
}
How can I get around this? The error is on this line:
SET Category = '${source.category}';
Is there a way I can pass a default value instead? Obviously, source
is available when the function runs, but I'm getting the error because source
within the original declared variable doesn't yet exist. Perhaps there's an obvious way of handling this, but it is escaping me.