首页 > 解决方案 > SQL 分配无限参数

问题描述

通常我们会使用下面这样的 SQL 查询,我们将传递带有预定义数字$1的参数

queryRunner.query('SELECT * FROM sample_data WHERE code IN ($1)', ['1'])

但是我想在没有预先定义的情况下传递多个参数$1。有什么办法可以解决这个问题?

queryRunner.query('SELECT * FROM sample_data WHERE code IN ($$)', ['1','2','3'])

标签: javascriptsql

解决方案


One approach dynamically builds the IN clause based on the expected number of parameters. Consider:

var params = ['1','2','3'];
var inClause = '?' + ', ?'.repeat(params.length - 1);
var sql = 'SELECT * FROM sample_data WHERE code IN (' + inClause + ')';
console.log(sql);

Once we have a statement with the right number of placeholders, we can simply bind the collection or array with no trouble.


推荐阅读