【问题标题】:Node.js and MSSQL stored proceduresNode.js 和 MSSQL 存储过程
【发布时间】:2021-04-06 14:13:19
【问题描述】:

从 Node.js 调用 MSSQL SP 的建议方法是什么(如果可能的话)。文档https://www.npmjs.org/package/mssql 很棒,但在任何地方都没有提到 SP(存储过程)。

【问题讨论】:

  • 是的,它确实提到了存储过程。在您已链接的网页中按 ctrl+F

标签: sql sql-server node.js


【解决方案1】:

linked document 确实提到了存储过程:

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);
    });

不确定回答这个问题是否明智,但它可能对未来的读者/谷歌人有价值。

【讨论】:

  • 我的错,感谢您的时间
  • 嗨@david Mulder..我正在尝试执行一个不接受任何参数但返回一个表的存储过程..为了获得响应应该进行哪些更改?
  • 那如何查看返回值呢?我试过: var parm = request.output('output_parameter').value 和 var parm = request.output('output_parameter').value 但得到 [object] 或未定义。
【解决方案2】:

随着 ES6/7 对 JS 的添加,它变得更好了。这就是你可以用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
  }
};

【讨论】:

    【解决方案3】:

    备用异步/等待语法。我喜欢 .then() 格式。

    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
          }
        });
    });
    

    【讨论】:

    • 为什么要混合两者?我只在必要时才这样做,比如承诺一个基于事件的库......这似乎可以工作,但增加了关于在哪里设置断点与@vitkon 的答案直接通过的混淆(只要它是一个单个请求)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2011-04-18
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多