2012-04-18 14 views
22

Estoy intentando recorrer una matriz entera (integer[]) en una función plpgsql. Algo como esto:Iteración sobre entero [] en PL/pgSQL

declare 
    a integer[] = array[1,2,3]; 
    i bigint; 
begin 
    for i in a 
loop 
    raise notice "% ",i; 
end loop; 
return true; 
end 

En mi caso uso real de la matriz entera a se pasa como parámetro a la función. Obtengo este error:

ERROR: syntax error at or near "$1" 
LINE 1: $1 

¿Cómo recorrer la matriz correctamente?

Respuesta

50
DECLARE 
    a integer[] := array[1,2,3]; 
    i integer;     -- int, not bigint! 
BEGIN 
FOR i IN 1 .. array_upper(a, 1) 
LOOP 
    RAISE NOTICE '%', a[i];  -- single quotes! 
END LOOP; 
RETURN TRUE; 
END 

O pruebe el new FOREACH in PostgreSQL 9.1:

FOREACH i IN ARRAY a 
LOOP 
    RAISE NOTICE '%', i; 
END LOOP; 

soluciones Sin embargo, basadas en conjuntos con generate_series() o unnest() son a menudo más rápido que un bucle para grandes conjuntos.

ejemplos básicos:

buscar en los etiquetas o por más.

+0

ahora estoy pasando la matriz a la función como 'f (matriz [1,2,3,4])' ¿hay alguna manera mejor de pasar una matriz a una función? –

+3

'f ('{1,2,3,4}' :: int [])' es * otra * manera. ¿Mejor? - ¡tú decides! –

Cuestiones relacionadas