共用方式為


INVALID_ARRAY_INDEX錯誤類別

SQLSTATE:22003

索引 <indexValue> 超出界限。 陣列具有 <arraySize> 元素。 使用 SQL 函式 get() 可容許在無效索引處存取元素,並改為傳回 Null。 如有必要,請將 設定 <ansiConfig> 為 「false」 以略過此錯誤。

參數

  • indexValue:要求之索引進入陣列。
  • arraySize:陣列的基數。
  • ansiConfig:要改變 ANSI 模式的組態設定。

解釋

不同于element_atelt,使用arrayExpr[indexValue]語法的陣列參考 indexValue 必須介於第一個專案和 arraySize - 1 最後一個專案之間 0

不允許負 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;