다음을 통해 공유


INVALID_ARRAY_INDEX 오류 클래스

SQLSTATE: 22003

<indexValue> 인덱스가 범위를 벗어났습니다. 배열에는 <arraySize> 요소가 있습니다. SQL 함수 get() 사용하여 잘못된 인덱스에서 요소에 액세스하는 것을 허용하고 대신 NULL을 반환합니다. 필요한 경우 이 오류를 피하기 위해 set<ansiConfig>을 "false"로 설정합니다.

Parameters

  • indexValue: 배열에 요청된 인덱스입니다.
  • arraySize: 배열의 카디널리티입니다.
  • ansiConfig: ANSI 모드를 변경하는 구성 설정입니다.

설명

element_atelt와 달리, 배열에 대한 참조 indexValuearrayExpr[indexValue] 구문을 사용하여야 하며, 첫 번째 요소인 0부터 마지막 요소인 arraySize - 1까지의 사이에 있어야 합니다.

음수 indexValue 또는 arraySize보다 크거나 같은 값은 허용되지 않습니다.

완화

이 오류의 완화 방법은 의도에 따라 달라집니다.

  • 제공된 indexValue이(가) 1부터 시작하는 인덱싱을 가정하나요?

    element_at(arrayExpr, indexValue), elt(arrayExpr, indexValue)' 또는 arrayExpr[indexValue - 1] 사용하여 올바른 배열 요소를 확인합니다.

  • indexValue이 음수이면 배열의 끝에서 요소를 검색하는 것으로 예상됩니까?

    element_at(arrayExpr, indexValue) 또는 elt(arrayExpr, indexValue)'를 사용합니다. 필요한 경우 1부터 시작하는 인덱싱을 조정합니다.

  • 인덱스의 카디널리티 범위를 벗어나는 요소에 대해 반환할 NULL 값을 get 예상합니까?

    식 표현을 변경할 수 있는 경우, try_element_at(arrayExpr, indexValue + 1)를 사용하여 배열 범위를 벗어난 참조를 처리할 수 있습니다. try_element_at의 1부터 시작하는 인덱싱을 유념하세요.

    식 표현을 변경할 수 없는 경우, 마지막 수단으로 set을 ansiConfig에서 false로 일시적으로 변경하여 경계를 벗어난 참조를 허용합니다.

예제

-- 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;