NodeJS MSSQL .query返回记录集和记录集中的双数据

时间:2017-08-02 14:44:00

标签: sql-server json node.js

我在节点中从mssql返回的JSON中看到所有数据行重复两次:

{
        "recordsets": [[{
                    "student_firstname": "Jonah                ",
                    "student_lastname": "Hill                    "
                }, {
                    "student_firstname": "Debra                   ",
                    "student_lastname": "Smith               "
                }
            ]],
        "recordset": [{
                "student_firstname": "Jonah                ",
                "student_lastname": "Hill                    "
            }, {
                "student_firstname": "Debra                   ",
                "student_lastname": "Smith               "
            }
        ],
        "output": {},
        "rowsAffected": [2]
    }

我暂时更改了查询以获取两行,以查看是否所有行都是重复的,并且它们如上所示。

function getStudent(studentID) 
{
    console.log("---------getStudent"); 


    sql.on('error', err => {
        // ... error handler 
        console.log("DB Error2: " + err); 
    })


    return sql.connect(config).then(pool => {
            // Query 
            return pool.request()
            .input('input_parameter', sql.Int, studentID)
            //.query('select student_firstname, student_lastname from students where student_id = @input_parameter')
            .query('select student_firstname, student_lastname from students where student_id in (31,32)')
        }).then(function(result) {
            console.log("getStudent:then(result=>"); 
            console.dir(result);
            sql.close(); 
            return result; 
        })
        .catch(err => {
            // ... error checks 
            console.log("DB Error1: " + err); 
            sql.close(); 
            throw err; 
        })

}

在app.get语句中调用上述函数,该语句返回JSON。

console.dir(result)显示与上面的JSON相同,除了在第一行显示" [Object]:所以我不认为它进一步包装了JSON。

{ recordsets: [ [ [Object], [Object] ] ],
  recordset:
   [ { student_firstname: 'Jonah                  ',
       student_lastname: 'Hill                    ' },
     { student_firstname: 'Debra                   ',
       student_lastname: 'Smith                   ' } ],
  output: {},
  rowsAffected: [ 2 ] }

我可以使用这样的数据,但它会浪费带宽。

3 个答案:

答案 0 :(得分:3)

数据未重新调整两次,只是通过两个属性公开。 recordset属性只显示recordsets中的第一个记录集。

mssql documentation

result.recordsets.length // count of recordsets returned by the procedure
result.recordsets[0].length // count of rows contained in first recordset
result.recordset // first recordset from result.recordsets

答案 1 :(得分:1)

代替

console.dir(result);

尝试:

console.dir(result.recordsets);

答案 2 :(得分:0)

您可以使用以下查询获取列数据:

result.recordset[0].student_firstname  // returns the value of the student firstname of first row
result.recordset[0].student_lastname   // returns the value of the student lastname of first row