Siraj ul Haq
Siraj ul Haq

Reputation: 885

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.

Upvotes: 0

Views: 850

Answers (3)

Siraj ul Haq
Siraj ul Haq

Reputation: 885

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

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

Upvotes: 0

Muhammad Ahsan Ayaz
Muhammad Ahsan Ayaz

Reputation: 1947

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.

Upvotes: 0

Hafiz Arslan
Hafiz Arslan

Reputation: 473

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

    // ...
});

Upvotes: 0

Related Questions