简体   繁体   中英

Inserting data using Prepare statement doesn't return inserted record

I am using node-sql . recordSet is undefined when i try to insert record in a table using Prepare Statement. Below is the sample line of code.

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

Although record is successfully inserted into database but it gives me undefined variable in callback function.

You didn't share what your statement actually do. however if you are inserting record using prepare statements. then instead of recordSet you can use "returnValue" or "affected" call back parameters. As node-sql states record set will have values if you are running selection queries that will return some recordSet. See

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

    // ...
});

According to node-mssql documentation (I've gone through it all, believe me) , the recordset or recordsets are sets returned when you execute a select query. Since you are executing an insert query, it is most likely to be undefined. Because even if recordset has to be returned, it would be the whole set (including your newly inserted row) which isn't very useful in insertion :)

In short, if your query doesn't contain selection, you'll get recordset undefined. Hope this helps.

Yes i found an answer, We need to specify records to be returned using the OUTPUT clause. Like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM