【问题标题】:Oracle Node js - Javascript - Bind variable for IN clause in SQL statementOracle Node js - Javascript - SQL 语句中 IN 子句的绑定变量
【发布时间】:2016-01-21 18:16:39
【问题描述】:

我正在使用 Oracle 的 Node js 驱动程序。我知道如何在 SQL 语句中绑定简单变量,但是如何绑定使用 IN 子句的变量?

在下面的示例中,我的绑定变量是 :grp_ids,我想将它绑定到字符串数组。但是代码并没有产生预期的结果。

function test2()
{
  oracledb.getConnection(connInfo,
    function(err, connection)
    {
      if (err) {console.error(err.message); return; }
      var grpIds = '(\'0021\', \'1684\')';
      console.log(grpIds);
      connection.execute(`
        SELECT ag.grp_id, ag.grp_nm from acct_group ag
        WHERE ag.grp_id in :grp_ids`,
        {grp_ids: grpIds},
        function(err, result)
        {
          if (err) {console.error(err.message); return; }
          console.log(result.rows);
        });
    });
}

【问题讨论】:

    标签: javascript sql node.js oracle


    【解决方案1】:

    您可以这样做,我不知道如果您的 in 子句列表大小发生变化,它是否会给您带来“绑定变量”的性能优势。基本上你已经动态地建立了你的 sql 字符串。

    const boundVars = someParamArray.map((val, index) => ':param'+index);
    const boundVarsInClause = boundVars.join(',');
    const boundParams = {};
    boundVars.forEach((boundVar, index) => boundParams[boundVar.substr(1)] = req.platformKeys[index].vNumber);
    
    const myQuery = `select * from some_table where some_col in ${boundVars}`
    oracleThingMachingy.execute(myQuery, boundParams)
    

    【讨论】:

    • 这是一个更简单的例子:sql const names = ["name1", "name2", "name3"]; connection.execute(`WHERE TABLE.NAME IN (${names.map((name, index) => `:${index}`).join(", ")})`, names) source
    【解决方案2】:

    您不能像您指出的那样直接绑定变量,但是将 cursor_sharing 设置为 force 会增加 sql 语句可以共享的程度,并且应该减少所需的负载数量。

    尝试执行:

    ALTER session SET cursor_sharing=force
    

    在您的会话中运行查询之前。只要“IN CLAUSE”列表中的项目数量相同,就不需要后续加载。

    您可以使用 v$sql 跟踪语句被加载和执行的次数:

    select sql_text,
           loads,
           executions
    from v$sql order by last_active_time desc ;
    

    This blog 有助于了解您在更改游标共享级别时实际在做什么。我建议您确保在之后立即将 cursor_sharing 设置回它的默认值 EXACT,然后再执行进一步的 sql 以将 FORCE 保持在尽可能小的范围 - 它可以改变更复杂的 sql 语句的处理方式。

    【讨论】:

      【解决方案3】:

      您不能将 IN 子句中的值数组绑定到 Oracle DB,因为绑定值被视为单个数据单元。它不被视为可以解析为逗号分隔值的代码文本。

      您可能会在http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html 中找到有用的“在 IN 子句中绑定多个值”p169

      【讨论】:

      • 感谢克里斯的参考。我现在很清楚这个问题。
      猜你喜欢
      • 2014-03-09
      • 2016-03-22
      • 2015-03-10
      • 1970-01-01
      • 2012-11-17
      • 2013-06-25
      • 2014-12-31
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多