tediousjs / node-mssql

Microsoft SQL Server client for Node.js
https://tediousjs.github.io/node-mssql
MIT License
2.23k stars 468 forks source link

What is the way to dynamically add 'where' conditions? #1370

Closed SungKyuMM closed 2 years ago

SungKyuMM commented 2 years ago

According to the document, this method prevents SQL Injection.

pool.query`select A from test where C = ${test}`

but, sometimes I want to add 'where' conditions. I tried to add 'where conditions', but an error occurs because the prevention of SQL Injection

 if(data.num){
   addQuery =  `AND D = ${test}`;
}
 pool.query`select A from test where C = ${test}  ${addquery}`

How do I dynamically add conditions in this way?

dhensby commented 2 years ago

This library is not a query builder, so this kind of thing is not really supported.

If you want to add a dynamic query element like that you should use a manual parameterised query:

const request = pool.request();
request.input('paramName', test);
let query = 'SELECT * FROM table WHERE C = @paramName';
if (condition) {
  request.input('anotherParam', test);
  query += 'and D = @anotherParam';
}
request.query(query).then((result) => console.log(result));

There are also some docs around the template method and how that could be used here: #1060, which didn't get merged because I think it's bad practice and shouldn't be encouraged without a very strong understanding of what is going on.