I currently have the following function that works perfectly fine:
const sql = require('mssql');
const config = require('../../config/credentials');
const Hardware = function () { };
Hardware.prototype.create = function (body) {
return new sql.ConnectionPool(config).connect().then(function (pool) {
return pool.query
`SELECT *
FROM my_table
WHERE hardware_guid = ${id}
});
};
But I want "my_table" in the query to be a variable, like ${my_table}. If I do it in the same way, I get the following error:
Must declare the table variable "@param1"
Looking at the documentation of the mssql package (https://www.npmjs.com/package/mssql), specifically at the section of ConnectionPool, I can see that they declare this parameters in the following way:
const sql = require('mssql')
sql.connect(config).then(pool => {
// Query
return pool.request()
.input('input_parameter', sql.Int, value)
.query('select * from mytable where id = @input_parameter')
}).then(result => {
console.dir(result)
}).catch(err => {
// ... error checks
})
sql.on('error', err => {
// ... error handler
})
So I tried to do something similar, this is what I did:
var sql = require("mssql")
var config = require("./test");
var id='1'
const pool1 = new sql.ConnectionPool(config);
pool1.connect().then(pool => {
return pool1.request() // or: new sql.Request(pool1)
.input('mytable', sql.NVarChar, 'nvs_central.software_governance')
.query(`SELECT *
FROM @mytable
WHERE software_guid = ${id}`)
}).then(result => {
console.dir(result)
}).catch(err => {
console.dir(err)
});
pool1.on('error', err => {
console.dir(err)
});
But I still get the "Must declare the table variable "@mytable" error. Note that if I replace "@mytable" in that last piece of code for "my_table_name" (so I put the actual name of the table instead of a variable/parameter) it retrieves the expected data perfectly fine.
So what do I need to do?
Thanks!