Skip to content
Advertisement

How to Insert bulk Array of data in mssql table using nodejs

I am using node-mssql, LInk : https://www.npmjs.com/package/mssql

i want to insert bulk array of data in mssql database

i am getting array of array records eg: [[row1],[row2],[row3]]

i want to insert these records in mssql database

import * as sql from "mssql";

const conn = new sql.ConnectionPool({
   user: "XXXXXXXXX",
   password: "XXXXXXXXXXX",
   server: "XXXXXXXXXXX",
   database: "TESTDATA",
   options: {
    instanceName: "XXX"
   },
   pool: {
     max: 10,
     min: 0,
     idleTimeoutMillis: 30000
   }
 });

conn.connect()

var values = [[john,1,4,80],[jenny,2,4,78],[abhi,3,4.60],[ram,4,4,90]]

new sql.Request(conn)
    .query(`INSERT INTO CLASS_TABLE (NAME, ROLL, CLASS, MARKS) VALUES
 ${values.map(row=>{ var num = Array('(' + row.join() + ')' ).join(); return num })}`)

Error : The label ‘@’ has already been declared. Label names must be unique within a query batch or stored procedure.

Advertisement

Answer

Use bulk

const table = new sql.Table('CLASS_TABLE');
table.columns.add('NAME', sql.NVarChar(15), {nullable: false});
table.columns.add('ROLL', sql.Int, {nullable: false});
table.columns.add('CLASS', sql.Int, {nullable: false});
table.columns.add('MARKS', sql.Int, {nullable: false});

values.forEach(arr => table.rows.add.apply(null, arr));

const request = new sql.Request();
request.bulk(table, (err, result) => {
  // ... error checks
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement