Construct prepared sql template with node-mssql in NodeJS

53 Views Asked by At

I have an Express app and I'm using the node-mssql library to connect to a mssql DB for retrieving and writing data from it.

Now, in the backend of the Express app I want to have a functionality that receives an optional set of field values that correspond to a table schema in the DB and with which I want to execute a simple Select with a Where Clause.

I want the functionality to be as flexible as possible which is why I assume I don't know which set of field values I receive beforehand and, therefore, want to build a prepared sql template that should be filled based on the received field values.

Basically I want to achieve what is described in this thread SQL WHERE column = everything

So the result should be:

If any field values are provided in the set then it should execute the prepared sql statement with these field values in the Where clause only.

If no field values are provided then it should execute the prepared sql with no restrictions on the Where clause. This would essentially be the same as executing the same sql statement just without a Where clause.

I believe there's an elegant solution to this without writing two different sql statements and then having a check whether any field values were provided in the set or not and then choose which sql statement is the correct one.

From the above thread, I've already found out that the solution SELECT * FROM table WHERE column = column works for me in a sql client and I could imagine setting column as the default value in the Express app if no field value is provided.

However, I'm not sure how to provide this type (column) to node-mssql and to make it interpreting it properly.

0

There are 0 best solutions below