INVALID_ARRAY_INDEX 错误类

SQLSTATE: 22003

索引 <indexValue> 超出界限。 数组具有 <arraySize> 个元素。 使用 SQL 函数 get() 容许访问无效索引上的元素,并改为返回 NULL。 如有必要,请将 <ansiConfig> 设置为“false”以绕过此错误。

参数

  • indexValue:数组中请求的索引。
  • arraySize:数组的基数。
  • ansiConfig:更改 ANSI 模式的配置设置。

说明

element_atelt 不同,使用 arrayExpr[indexValue] 语法对数组的引用 indexValue 必须介于第一个元素的 0 和最后一个元素的 arraySize - 1 之间。

不允许使用负 indexValue 或大于或等于 arraySize 的值。

缓解

此错误的缓解措施取决于意图:

示例

-- An INVALID_ARRAY_INDEX error because of mismatched indexing
> SELECT array('a', 'b', 'c')[index] FROM VALUES(1), (3) AS T(index);
  [INVALID_ARRAY_INDEX] The index 3 is out of bounds. The array has 3 elements. If necessary set "ANSI_MODE" to false to bypass this error.

-- Using element_at instead for 1-based indexing
> SELECT element_at(array('a', 'b', 'c'), index) FROM VALUES(1), (3) AS T(index);
  a
  c

-- Adjusting the index to be 0-based
> SELECT array('a', 'b', 'c')[index -1] FROM VALUES(1), (3) AS T(index);

-- Tolerating out of bound array index with adjustment to 1-based indexing
> SELECT try_element_at(array('a', 'b', 'c'), index + 1) FROM VALUES(1), (3) AS T(index);
  b
  NULL

-- An INVALID_ARRAY_INDEX error because of negative index
> SELECT array('a', 'b', 'c')[index] FROM VALUES(-1), (2) AS T(index);
  [INVALID_ARRAY_INDEX] The index -1 is out of bounds. The array has 3 elements. If necessary set "ANSI_MODE" to "false" to bypass this error.

-- Using element_at to index relative to the end of the array
> SELECT element_at(array('a', 'b', 'c'), index) FROM VALUES(-1), (2) AS T(index);
  c
  b

-- Tolerating an out of bound index by setting ansiConfig in Databricks SQL
> SET ANSI_MODE = false;
> SELECT array('a', 'b', 'c')[index] FROM VALUES(1), (3) AS T(index);
  b
  NULL
> SET ANSI_MODE = true;

-- Tolerating an out of bound index by setting ansiConfig in Databricks Runtime
> SET spark.sql.ansi.enabled = false;
> SELECT array('a', 'b', 'c')[index] FROM VALUES(1), (3) AS T(index);
  b
  NULL
> SET spark.sql.ansi.enabled = true;