简体   繁体   中英

Generating SQL query that will ignore where clause if no condition is given in it using sequelize & node.js

I am using node.js as backend language & Microsoft SQL as database. And I am using sequelize ( http://docs.sequelizejs.com ) to query with SQL. Below is my Web API route handler code :

const sequelize = require('sequelize');

module.exports = {
getinfo(req, res) {
  let {search, id, fromDate, toDate, firstName, lastName} = req.body;
  const condition = "";

  if(search != null && search != '')
  {
      condition += "id LIKE '%" + search + "%'";
      condition += "fromDate LIKE '%" + search + "%'";
      condition += "toDate LIKE '%" + search + "%'";
      condition += "firstName LIKE '%" + search + "%'";
      condition += "lastName LIKE '%" + search + "%'";
  }

  if(fromDate != null && toDate != null && fromDate != '' && toDate != '')
  {
      condition += "date BETWEEN" + fromDate + "AND" + toDate;
  }

  const query = "";
  query = " SELECT * from TABLE where" + condition;
  sequelize.query(query, type: sequelize.QueryTypes.SELECT)
  .then( ...)

 }
}

I wanted to make a scenario where even if condition is empty, the query should return the database. Initially I thought of using if in condition variable to check if condition variable has anything there or not.

if(condition != '' && condition != null) {
    query = " SELECT * from TABLE where" + condition;
} else {
    query = " SELECT * from TABLE " ;
}

But it wasn't working as expected (due to asynchronous nature of JavaScript). I want to make an SQL query itself that will check if there is any condition present in where clause or not, if not then it should return the whole table. Any help would be appreciated

The standard trick is to prepend 1=1 to the list of conditions. And (maybe) later append the extra conditions using AND condition :


const condition = " 1=1";

  if(search != null && search != '')
  {
      condition += " AND id LIKE '%" + search + "%'";
      condition += " AND fromDate LIKE '%" + search + "%'";
      condition += " AND toDate LIKE '%" + search + "%'";
      condition += " AND firstName LIKE '%" + search + "%'";
      condition += " AND lastName LIKE '%" + search + "%'";
  }

  if(fromDate != null && toDate != null && fromDate != '' && toDate != '')
  {
      condition += " AND date BETWEEN " + fromDate + " AND " + toDate;
  }

  const query = "";
  query = " SELECT * from TABLE where" + condition;
  sequelize.query(query, type: sequelize.QueryTypes.SELECT) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM