0

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.

3 Answers 3

2

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
});
Sign up to request clarification or add additional context in comments.

5 Comments

ERROR: Cannot read property 'push' of null", I am getting this Error if array is this [[john,1,4,80],[jenny,2,null,78],[abhi,3,4.60],[ram,4,4,null]]
@SaiJeevanBalla the example you gave all had values, if some columns can be null then you can just adjust {nullable: false} to {nullable: true} for those ones.
can you help me out of this ERROR: RequestError: Connection lost - read ECONNRESET, while inserting bulk data in mssql table it will lost the connection
What if you want to insert into an existing table and don't want to specify the column type for each column? I.e. when you are devloping a generic framework, with table names and columns not known upfront?
@Ya. for this particular library, you must to define the column type. And, to be honest, I don't think you'll find many frameworks that won't at least require the consumer to provide the column type in some manner e.g. perhaps even just by inspecting the data type being passed? e.g. if it's a string value, assume NVarChar(len), if int assume Int, if float presume Float etc.
1

Better answer:

import {
  ConnectionPool,
  Table,
  VarChar,
  Int,
} from 'mssql';

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

const table = new Table('CLASS_TABLE');
table.create = false;
// Ignore the identity field
table.columns.add('NAME', VarChar, { nullable: true });
table.columns.add('ROLL', Int, { nullable: true });
table.columns.add('CLASS', Int, { nullable: true });
table.columns.add('MARKS', Int, { nullable: true });

for (let j = 0; j < values.length; j += 1) {
  table.rows.add(
    values[j][0],
    values[j][1],
    values[j][2],
    values[j][3]
  );
}
const request = pool.request();

const results = await request.bulk(table);
console.log(`rows affected ${results.rowsAffected}`);

2 Comments

Can you write a bit about what's happening in this code that makes it superior to the other answer?
yes, the other examples did not work. the main enhancement is table.rows.add( values[j][0], values[j][1], values[j][2], values[j][3] );
0

Update to Williams answer:

import {
ConnectionPool,
Table,
VarChar,
Int,
} from 'mssql';
let values = [[john,1,4,80],[jenny,2,4,78],[abhi,3,4,60],[ram,4,4,90]];
const table = new Table('CLASS_TABLE');
table.create = false;
// Ignore the identity field
table.columns.add('NAME', VarChar, { nullable: true });
table.columns.add('ROLL', Int, { nullable: true });
table.columns.add('CLASS', Int, { nullable: true });
table.columns.add('MARKS', Int, { nullable: true });
//If you have an array of arrays you can map it without hard coding the amount of values needed
//for (let j = 0; j < values.length; j += 1) {
// table.rows.add(
//    values[j][0],
//    values[j][1],
//    values[j][2],
//    values[j][3]
//  );
//}

//Updated way allows for dynamically added columns coming from something like a config file
values.forEach(row => table.rows.add.apply(table.rows,row));
const request = pool.request();
const results = await request.bulk(table);
console.log(`rows affected ${results.rowsAffected}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.