Search code examples
javascriptsqlnode.jsexpress

SQL Server returning results twice on a single call?


I have connected a SQL Server database to a simple node.js server. When I run the code I get both recordsets and recordset returned to me. They both essentially contain the same data. I can work with this but it seems redundant and would be neater to just call exactly the records I need.

I was hoping to get an clear ELI5 explanation as mssql npm documentation is somewhat confusing in my opinion.

Here is the code below:

const express = require('express');
const cors = require('cors');
const sql = require('mssql');
const app = express();
const sqlServer = 'hasea\\SQLExpress'

const selectAllQuery = 'SELECT * FROM dbo.users';
const config = {
    user: 'nbar',
    password: 'nb',
    server: sqlServer,
    database: 'nirvanaBar'
}

// SQL Select function
function DBconn(query, res) {

    sql.connect(config, function (err) {
        if (err) console.log(err);
        var request = new sql.Request();

        request.query(query, function (err, row) {
            if (err) console.log(err)
            res.json({
                data: row
            })
        })
    })
}
app.use(cors());

app.get('/', (req, res) => {
    res.send("Hello from the server")
});

app.get('/users', (req, res) => {
    //query?
    //var andrew = "select * from dbo.users where firstName = 'Andrew';"
    var matt = "select * from dbo.users where firstName = 'Matt';"
    //DBconn(selectAllQuery,res);
    DBconn(matt, res);

})
app.listen(4000, () => {
    console.log(`Server started on port 4000`)
})

The results:

enter image description here

I can see this has being brought up before but I am not understanding what is going on nor does the documentation provide much information as to why this would be the case. I can use the data, I just thought it would be neater to return both recordsets and recordset.

Thanks in advance


Solution

  • This is the expected behaviour of mssql have a look at the documentation here. When you execute multiple statements it allows you to have multiple recordsets

    You will notice that there is in fact 2 properties

    recordset (singular) and recordsets (plural)

    recordset (singular) refers to the first statement that is executed. In your case you can just use this

    recordsets (plural) is an array of recordsets, in your case there will only be one in the array as you are only running one statement.