Oracle Node js - Javascript - SQL 语句中的 IN 子句绑定变量

Oracle Node js - Javascript - Bind variable for IN clause in SQL statement

本文关键字:IN 子句 绑定 变量 语句 Node js Javascript SQL Oracle      更新时间:2023-09-26

我正在使用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);
        });
    });
}

你可以这样做,我不知道如果你的子句列表,大小发生变化,它是否会给你带来"绑定变量"的性能优势。基本上,您已经动态地构建了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)

您不能像您指出的那样直接绑定变量,但是将cursor_sharing设置为强制会增加 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 ;

此博客有助于了解更改游标共享级别时实际执行的操作。我建议您确保在执行进一步的 sql 之前立即将cursor_sharing设置回默认值 EXACT 以将 FORCE 保持在尽可能小的范围 - 它可以更改更复杂的 sql 语句的处理方式。

不能将

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

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