使用 Prepare 语句插入数据不会返回插入的记录

Inserting data using Prepare statement doesn't return inserted record

本文关键字:插入 返回 记录 数据 Prepare 语句 使用      更新时间:2023-09-26

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

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

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

您没有分享您的陈述的实际作用。 但是,如果您使用 Prepare 语句插入记录。 那么您可以使用"returnValue"或"受影响的"回调参数代替 recordSet。由于节点 sql 状态,如果运行将返回某些 recordSet 的选择查询,则记录集将具有值。看

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 文档(相信我,我已经完成了所有内容),记录集是执行选择查询时返回的一个或多个记录集。由于您正在执行插入查询,因此它很可能是未定义的。因为即使必须返回记录集,它也将是整个集(包括新插入的行),这在插入:)中不是很有用

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

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

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