【问题标题】:Correct Nodejs mssql parameterized LIKE query syntax正确的 Nodejs mssql 参数化 LIKE 查询语法
【发布时间】:2017-04-14 17:51:11
【问题描述】:

对SQL Server使用Nodejs和mssql包,我理解带参数的普通SELECT查询:

aVar = "somestring"; // used as example, the real input is from a web form
request = new sql.Request(conn)
.input('aParam', sql.NVarChar(200), aVar);
q = "SELECT * FROM myTable WHERE theColumn = @aParam";
request.query(q, function(err, record) { ...

那些工作得很好。将其更改为使用LIKE,但我无法让它工作。我已经尝试在 % 字符之前、之后、在它周围、在字符串周围、整个事物等周围使用单引号。这样做:

q = "SELECT * FROM myTable WHERE theColumn LIKE " + "'%@aParam%'";

不会导致任何错误,但不会返回任何结果。所有其他使用这些单引号的尝试都会导致查询语法错误。我似乎找不到任何使用通配符参数化查询的文档。我哪里错了?

【问题讨论】:

    标签: sql-server node.js wildcard parameterized


    【解决方案1】:

    这里提到了执行此操作的语法 - https://github.com/tediousjs/node-mssql/issues/332

    但总之:

    q = `SELECT * FROM myTable WHERE theColumn LIKE '%' + @aParam + '%';`;
    

    【讨论】:

      【解决方案2】:

      除非您编写低级驱动程序/工作者,否则我建议使用任何 ORM:

      const Sequelize = require('sequelize');
      const sequelize = new Sequelize('database', 'username', 'password');
      
      const MyTable = sequelize.define('myTable', {
        theColumn: Sequelize.STRING
      });
      
      const aVar = 'somestring'; 
      
      const results = await MyTable.findAll({
          where: {
              theColumn: { $like: `%${aVar}%` }
          }
        });
      })
      console.dir(results);
      

      await 只能在 async 函数中使用。对于支持开箱即用的框架,请查看 Koa.js https://github.com/koajs/koa

      【讨论】:

      • 欣赏 ORM 建议,我可能最终会转向该建议,但希望使用当前的 mssql 包找到解决方案。
      猜你喜欢
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      相关资源
      最近更新 更多