How to use the query function from mssql

Find comprehensive JavaScript mssql.query code examples handpicked from public code repositorys.

137
138
139
140
141
142
143
144
145
146
147
    res.json(results.recordset);
  });
});


app.get('/select-static', (req, res) => {
  sql.query('SELECT GETDATE()', (err, results) => {
    if (err) {
      log('Failed to execute select query.', err);
      return res.status(500).json(err);
    }
fork icon34
star icon66
watch icon0

23
24
25
26
27
28
29
30
31
32

    // SQL 데이터베이스에 연결한다.
    await sql.connect('mssql://username:password@localhost/database');

    // http 요청 본문으로 받은 user_id 매개변수를 가지고 데이터베이스에 질의한다.
    const result = await sql.query('SELECT * FROM users WHERE USER = ' + user_id);

    // 요청자에게 HTTP 응답을 통해 SQL 질의 결과를 반환한다.
    return res.json(result);
})
fork icon7
star icon31
watch icon2

+ 7 other calls in file

27
28
29
30
31
32
33
34
35
36
function executar(instrucao) {
    // VERIFICA A VARIÁVEL DE AMBIENTE SETADA EM app.js
    if (process.env.AMBIENTE_PROCESSO == "producao") {
        return new Promise(function (resolve, reject) {
            sql.connect(sqlServerConfig).then(function () {
                return sql.query(instrucao);
            }).then(function (resultados) {
                console.log(resultados);
                resolve(resultados.recordset);
            }).catch(function (erro) {
fork icon0
star icon10
watch icon1

+ 13 other calls in file

28
29
30
31
32
33
34
35
36
37
  const sql =
    /* sql*/
    `SELECT salary, emp_name, bonus, job_id, hire_date
      FROM employee WHERE emp_name = 'Liu Bei' AND salary > 10000
      ORDER BY salary DESC`
  const result = await mssql.query(sql)
  console.log(result.recordset)
  mssql.close()
} catch (error) {
  console.log(error)
fork icon3
star icon6
watch icon3

+ 5 other calls in file

126
127
128
129
130
131
132
133
134
135
            enableArithAbort: true,
            tedious: true
        }
    });

    return (await sql.query(gettableandcolumnlist)).recordset;
} catch (err) {
    console.log(err);
    return err;
}
fork icon0
star icon3
watch icon2

+ 5 other calls in file

15
16
17
18
19
20
21
22
23
24
        var quals=req.body.quals;
        var insert = '';
        quals.forEach((subId)=>{
            insert+=`insert into qualifications values('${subId}', '${name}');`
        })            
        var query = await sql.query(insert);
        }
    }
    return res.status(200).json({query})
}catch(err){
fork icon1
star icon1
watch icon0

+ 7 other calls in file

9
10
11
12
13
14
15
16
17
18
const createSubDev = async (req, res) =>{
    try{
        if(!req.body.startDate || !req.body.endDate){
            throw new Error('Incorrect date information supplied')
        }
        const result = await sql.query(`insert into subDev values('${req.params.subId}','${req.params.academicId}','${req.body.startDate}','${req.body.endDate}')`)
        res.status(200).json({result})
    }catch(err){
        res.status(500).json({message: err.message})
    }
fork icon1
star icon1
watch icon0

5
6
7
8
9
10
11
12
13
14
15
}


const getInstancesSchedule = async(req,res)=>{
    try{
        var query = `select id, subId, enrolments, datepart(yyyy, startDate) as year, datepart(m, startDate) as month from instances order by year, subId, month;`;
        var data = await sql.query(query)
        res.status(200).json(data.recordset)
    }
    catch(err){
        res.status(500).json({message: err.message})
fork icon1
star icon1
watch icon0

+ 3 other calls in file

10
11
12
13
14
15
16
17
18
19
const updateAssignments = async(req, res) =>{
    try{
        //delete existing assignments
        var deleteQuery = `delete assignments from assignments join instances on assignments.instanceId=instances.id
         where assignments.academicId='${req.params.id}'and startDate='${req.body.yearMonth}';`;
        const deleteData = sql.query(deleteQuery);
        const assignments = req.body.assignments
        var insert = '';
        //builds query to enter all desired assignments
        assignments.forEach((assignment)=>{
fork icon1
star icon1
watch icon0

80
81
82
83
84
85
86
87
88
89

var _id: string = req.params._id;

sql.connect(db)
  .then(function(connection) {
    sql.query
      `DELETE FROM Course WHERE courseID = ${_id}`
      .then(function(result) {
        new ActivityService().reportActivity('course', 'Course Deleted', 'success', _id, currentUserID, 'Course has been deleted.');
        res.send({ result: "success", title: "Course Deleted", msg: "Course has been deleted successfully.", serverMsg: "" });
fork icon1
star icon0
watch icon4

+ 5 other calls in file

106
107
108
109
110
111
112
113
114
115
        };
        yield mssql.connect(dbConfig);
        for (let i = 0; i < QueryConditionArray.length; i++) {
            var SQL = ` // Your SQL query goes here
${QueryConditionArray[i]}`;
            const result = yield mssql.query(SQL);
            // Clear the worksheet
            for (let j = worksheet.rowCount; j >= 1; j--) {
                worksheet.spliceRows(j, 1);
            }
fork icon0
star icon1
watch icon1

+ 25 other calls in file

41
42
43
44
45
46
47
48
49
50
const RepportError_1 = require("../../../middlewares/RepportError");
const NotifyByEmail_1 = require("../../../middlewares/NotifyByEmail");
const findAllUsers = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        yield MSSQL.connect(mssql_1.config);
        const result = yield MSSQL.query("SELECT * FROM ZBA010 WHERE D_E_L_E_T_ = ' '");
        let userDb = result.recordset;
        const users = [];
        userDb.forEach(element => {
            users.push({
fork icon0
star icon1
watch icon1

+ 38 other calls in file

23
24
25
26
27
28
29
30
31
32
export const TIME_GROUP_QUERY = (last, var_name = 'timestamp', group_var = '') => { return `AND ${var_name} > '${last}' GROUP BY ${group_var ? `[${group_var}], ` : ''}${TIMESTAMP(var_name)} ORDER BY ${TIMESTAMP(var_name)} ASC;` }

export let query = async (q: string) => {
  try {
    if (!connection) connection = await sql.connect(connection_config)
    return await sql.query(q)
  } catch (e) {
    console.log(e)
    // ... error checks
  }
fork icon3
star icon0
watch icon2

+ 3 other calls in file

48
49
50
51
52
53
54
55
56
57
  }
}
let resultado = null;
try {
    await sql.connect(sqlConfig);
    sql.query('select 1 as number').then((result) => {
        resultado = JSON.stringify(result.recordset[0].number);
        console.log('Resultado: '+resultado);
        res.setHeader('Content-Type', 'application/json');
        res.send(resultado);
fork icon0
star icon0
watch icon1

48
49
50
51
52
53
54
55
56
57
  }
}
let resultado = null;
try {
    await sql.connect(sqlConfig);
    sql.query(`select ${1} as number`).then((result) => {
        resultado = JSON.stringify(result.recordset[0].number);
        console.log('Resultado: '+resultado);
        res.setHeader('Content-Type', 'application/json');
        res.send(resultado);
fork icon0
star icon0
watch icon1

+ 10 other calls in file

107
108
109
110
111
112
113
114
115
116
117
    interactiveLoop();


}
async function runquery(script) {
    try {
        const result = await sql.query(script);
        showRecordset(result);
    } catch (err) {
        // ... error checks
        writeLog(err.message);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

12
13
14
15
16
17
18
19
20
21
22
23


endpoints.list = async (req, res,) => {
    try {


        let result =  [{recordset: wqProgress} , {recordset: feedbackProgress}, { recordset: adminlist},{ recordset: wqWorkProgress}] = await Promise.all([
            await sql.query(`select * from ${WQProgressModel}`),
            await sql.query(`select * from ${WQFeedback}`),
            await sql.query(`SELECT * FROM ${UserModel} where   (SubSection IN ('DS', 'DSB') or [ManagementCard] = '1')  and SubSection NOT IN ('DSA') and EMPL_STATUS NOT IN ('T', 'Archive')   order by First `),
            await sql.query(`SELECT * FROM ${WQCheckmarkModel} `)            
        ])
fork icon0
star icon0
watch icon1

+ 4 other calls in file

161
162
163
164
165
166
167
168
169
170
try {


const [{recordset: Type}, {recordset:Standard }]  = await Promise.all([
      await sql.query(`Select DISTINCT([Type]) from ${Model}`),
      await sql.query(`Select DISTINCT([Standard]) from ${Model}`),
       
])

let results = {
fork icon0
star icon0
watch icon1

+ 7 other calls in file

263
264
265
266
267
268
269
270
271
272

try {
  await sql.connect(config);
  const sql_command = `INSERT INTO VitalSignM (MedNo, UserNo, TakeTime, TakeType, TakeValue, Memo, DataUnit, AllowSync, SyncStatus, SyncTime) VALUES ('${medId}', '${userId}', '${takeTime}', '${takeType}', '${takeValue}', '${memo}', '${dataUnit}', 'Y', 'N', NULL)`;
  console.log(sql_command);
  const result = await sql.query(sql_command);
  console.log("sql result", result);
} catch (err) {
  console.error(err);
}
fork icon0
star icon0
watch icon1

+ 14 other calls in file

57
58
59
60
61
62
63
64
65
66
const sql = `SELECT TENDANGNHAP FROM TK_TAIXE WHERE MATX = '${driverId}'`;

const poolPromise = mssql.connect(config);
poolPromise
  .then(() => {
    return mssql.query(sql);
  })
  .then((result) => {
    return result.recordset[0];
  })
fork icon0
star icon0
watch icon1

+ 99 other calls in file