Procedimientos PL/PgSQL: Introducción

Bloques en Postgres

do $$
<<mi_bloque>>
declare
  film_count integer := 0;
begin
   -- Obtener el número de películas
   select count(*)
   into film_count
   from film;
   -- Mostrar un Mensaje
   raise notice 'El número de películas es: %', film_count;
end mi_bloque $$;

Condicionales

Los condicionales permiten ejecutar instrucciones en función del resultado de una expresión booleana.

  • found es una variable global que está disponible una vez ejecutado un select.

do $$
declare
  selected_film film%rowtype;
  input_film_id film.film_id%type := 93;
begin

  select * from film
  into selected_film
  where film_id = input_film_id;

  if not found then
     raise notice 'La película % no ha sido encontrada', input_film_id;
  else
     raise notice 'El título de la película es %', selected_film.title;
  end if;
end $$

Declaraciones if-then-elsif

Las declaraciones if y if-else evalúan una condición. Sin embargo, la if-then-elsif declaración evalúa múltiples condiciones.

do $$
declare
   v_film film%rowtype;
   len_description varchar(92);
begin

  select * from film
  into v_film
  where film_id = 100;

  if not found then
     raise notice 'Película no encontrada';
  else
      if v_film.length >0 and v_film.length <= 50 then
         len_description := 'Corta';
      elsif v_film.length > 50 and v_film.length < 120 then
         len_description := 'Normal';
      elsif v_film.length > 120 then
         len_description := 'larga';
      else
         len_description := 'No Disponible';
      end if;

      raise notice 'La película % es %.',
         v_film.title,
         len_description;
  end if;
end $$

Declaraciones CASE

Además de la declaración if, se proporciona declaraciones CASE que le permiten ejecutar un bloque de código basado en una condición.

Declaración de CASE simple

do $$
declare
    rate   film.rental_rate%type;
    price_segment varchar(50);
begin
    -- obtener la tasa de alquiler
    select rental_rate into rate
    from film
    where film_id = 100;

    -- asignar la clasificacion del segmento
    if found then
        case rate
           when 0.99 then
              price_segment = 'Econo';
           when 2.99 then
              price_segment = 'Regular';
           when 4.99 then
              price_segment = 'VIP';
           else
              price_segment = 'Sin Especificar';
           end case;
        raise notice 'El segmento de la pelicula es: %', price_segment;
    end if;
end; $$