使用 Prepare 语句插入数据不会 return 插入记录

Inserting data using Prepare statement doesn't return inserted record

我正在使用 node-sql。 当我尝试使用 Prepare 语句在 table 中插入记录时,记录集未定义。下面是示例代码行。

ps.execute(data, function (err, recordSet, affected) { });

虽然记录已成功插入数据库,但它在回调函数中给了我未定义的变量。

你没有分享你的声明实际上做了什么。但是,如果您使用 prepare 语句插入记录。那么您可以使用 "returnValue" 或 "affected" 回调参数代替 recordSet。 正如 node-sql 状态记录集将具有值,如果你是 运行 选择查询将 return 一些记录集。 参见

request.execute('record', function(err, recordsets, returnValue, affected) {
    // ... error checks

    console.log(recordsets.length); // count of recordsets returned by the procedure
    console.log(recordsets[0].length); // count of rows contained in first recordset
    console.log(returnValue); // procedure return value
    console.log(recordsets.returnValue); // same as previous line
    console.log(affected); // number of rows affected by the statemens
    console.log(recordsets.rowsAffected); // same as previous line

    console.log(request.parameters.output_parameter.value); // output value

    // ...
});

根据 node-mssql 文档(相信我,我已经全部看完了),一个或多个记录集是您执行 select 查询时返回的集合。 由于您正在执行插入查询,因此它很可能是未定义的。因为即使必须返回记录集,它也将是整个集合(包括您新插入的行),这在插入中不是很有用 :)

简而言之,如果您的查询不包含 selection,您将得到未定义的记录集。 希望这有帮助。

是的,我找到了答案,我们需要使用 OUTPUT 子句指定要返回的记录。喜欢:

INSERT INTO Table OUTPUT.Id VALUES(...);