//col list
let col = ["A", "B", "C"];
//Sample Object List
letsomeObj= [
{ A: 1, B: 2, C: 3 },
{ A: 1, B: 2, C: 3 },
{ A: 1, B: 2, C: 3 }
];
//function call..
this.createSqlQuery("PKTABLE", col, someObj);
createSqlQuery(tableName: string, columns: string[], obj: any) {
this.generatedSqlQuery = `INSERT INTO ${tableName} `
let columnList = "";
columnList = columnList + "("
for (let index = 0; index < columns.length; index++) {
if (index == columns.length - 1) {
columnList = columnList + columns[index];
} else {
columnList = columnList + columns[index] + ",";
}
}
this.generatedSqlQuery = this.generatedSqlQuery + columnList + ") VALUES ";
for (let index = 0; index < obj.length; index++) {
let item = obj[index];
if (index == columns.length - 1) {
this.generatedSqlQuery = this.generatedSqlQuery + "(";
for (var key in obj[index]) {
if (obj[index].hasOwnProperty(key)) {
var val = obj[index][key];
this.generatedSqlQuery = this.generatedSqlQuery + val + ",";
}
}
this.generatedSqlQuery = this.generatedSqlQuery.slice(0, -1);
this.generatedSqlQuery = this.generatedSqlQuery + ")";
if (index == columns.length - 1) {
this.generatedSqlQuery = this.generatedSqlQuery + ",";
}
if (obj.length == 1) {
this.generatedSqlQuery = this.generatedSqlQuery.slice(0, -1);
}
} else {
this.generatedSqlQuery = this.generatedSqlQuery + "(";
let length = 0;
for (var key in obj[index]) {
length++;
}
for (var key in obj[index]) {
if (obj[index].hasOwnProperty(key)) {
var val = obj[index][key];
this.generatedSqlQuery = this.generatedSqlQuery + val + ",";
}
}
this.generatedSqlQuery = this.generatedSqlQuery.slice(0, -1);
this.generatedSqlQuery = this.generatedSqlQuery + "),";
if (obj.length == 1) {
this.generatedSqlQuery = this.generatedSqlQuery.slice(0, -1);
}
}
}
if (obj.length > 1) {
this.generatedSqlQuery = this.generatedSqlQuery.slice(0, -1);
}
console.log(generatedSqlQuery);
return this.generatedSqlQuery;
}
Result Of Function :
INSERT INTO PKTABLE (A,B,C) VALUES (1,2,3),(1,2,3),(1,2,3)
Author Profile
-
PREM KUMAR
-
Hey Its..! Tech Lover , Ionic, Angular, Typescript, Dotnet Core, Node, Like Opencv, AI, ML, Robotics, Iot, Love Music, Cooking, Girls, Innovation
Latest Post by this Author