3

What would be the suggested way (if even possible) to call MSSQL SP from Node.js. The documentation https://www.npmjs.org/package/mssql is great but there is no mention of SP (stored procedure) anywhere.

user2896521
  • 275
  • 3
  • 4
  • 13

3 Answers3

11

The linked document does actually mention stored procedures:

var request = new sql.Request(connection);
    request.input('input_parameter', sql.Int, 10);
    request.output('output_parameter', sql.VarChar(50));
    request.execute('procedure_name', function(err, recordsets, returnValue) {
        // ... error checks

        console.dir(recordsets);
    });

Not sure it's wise to answer this question, but it might be valueable for future readers/googlers.

David Mulder
  • 26,123
  • 9
  • 51
  • 114
  • My bad, appreciate your time – user2896521 Sep 15 '14 at 20:27
  • hi @david Mulder.. i am trying to execute a stored procedure which doesn't accept any parameters but returns a table.. what changes should be made in order to get the response ? – freshtoUI Dec 24 '15 at 13:39
  • Then how do you check the return value? I tried: var parm = request.output('output_parameter').value and var parm = request.output('output_parameter').value but got [object] or undefined. – NealWalters Jul 28 '17 at 17:02
  • 1
    Using return values: https://stackoverflow.com/questions/28669183/how-to-access-the-output-parameter-in-node-mssql – NealWalters Jul 28 '17 at 17:11
4

It's getting better with ES6/7 additions to JS. This is how you can do it with async/await:

async function getDataFromProcedure(dbConfig, procedureName) {
  try {
    await sql.connect(dbConfig);
    const request = new sql.Request();
    recordsets = await request.execute(procedureName);
    return recordsets[0];
  } catch (error) {
    // handle error here
  }
};
vitkon
  • 1,058
  • 8
  • 13
0

Alternate async/await syntax. I like the .then() format.

return await this.sqlConnectionPool.connect().then(async (pool) => {
  return await pool
    .request()
    .input("UserID", sql.Int, id)
    .execute("spADF_User_Get")
    .then((result) => {
      if (result.recordset && result.recordset.length === 1) {
        return result.recordset[0];
      } else {
        //Something bad happened
      }
    });
});
strattonn
  • 1,790
  • 2
  • 22
  • 41
  • why mix the two? I only do it if I have to, like promisifying an event-based library... This seems like it would work but adds confusion about where to set the breakpoints vs. @vitkon's answer where it goes straight through (as long as it's a single request) – ps2goat May 11 '21 at 20:12