Hi @Elliot Stoner,
I used MSSQL bulk() in below code which worked for me:
import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import * as sql from "mssql";
const risqlcnfg = {
user: "username",
password: "Rpassword2",
server: "servername.database.windows.net",
database: "dbname",
options: {
encrypt: true,
trustServerCertificate: false,
},
};
const pools = new Map<string, Promise<sql.ConnectionPool>>();
async function getPool(): Promise<sql.ConnectionPool> {
if (!pools.has("default")) {
const pool = new sql.ConnectionPool(risqlcnfg);
pools.set("default", pool.connect());
}
return pools.get("default")!;
}
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
context.log("HTTP trigger function started.");
try {
if (!req.body || !Array.isArray(req.body.teams) || req.body.teams.length === 0) {
context.res = {
status: 400,
body: "Invalid request. Expected an array of teams with Season_ID and Team_Name",
};
return;
}
const ripl = await getPool();
const ri_tb = new sql.Table("Teams");
ri_tb.create = false;
ri_tb.columns.add("Season_ID", sql.TinyInt, { nullable: false });
ri_tb.columns.add("Team_Name", sql.VarChar(50), { nullable: false });
req.body.teams.forEach((team: { Season_ID: number; Team_Name: string }) => {
ri_tb.rows.add(team.Season_ID, team.Team_Name);
});
const rithsql = ripl.request();
await rithsql.bulk(ri_tb);
context.res = {
status: 200,
body: `Successfully inserted ${req.body.teams.length} teams.`,
};
} catch (ex: any) {
context.log.error("SQL Error:", ex);
context.res = {
status: 500,
body: `Database error: ${ex.message}`,
};
}
};
export default httpTrigger;
Output:
In Post call, the body (array of json) which i sent :
{
"teams": [
{ "Season_ID": 1, "Team_Name": "Rithwik" },
{ "Season_ID": 1, "Team_Name": "Bojja" },
{ "Season_ID": 2, "Team_Name": "Chotu" }
]
}
Hope this helps.
If the answer is helpful, please click Accept Answer and kindly upvote it. If you have any further questions about this answer, please click Comment.