I wrote a PLpgSQL function which should return SETOF products
table:
CREATE OR REPLACE FUNCTION get_products_by_category
(selected_category_id smallint DEFAULT 1) RETURNS SETOF products AS
$BODY
$BEGIN
RETURN QUERY (SELECT * FROM products WHERE CategoryID = selected_category_id);
END;
$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100
ROWS 1000;
And next I want to iterate over results in another function (non-finished view, because I try to add in PgAdmin III and I have errors):
DECLARE
R RECORD;
BEGIN
IF TG_TABLE_NAME != 'Categories' THEN
RAISE 'This trigger function is for Categories, but was called for %', TG_TABLE_NAME;
FOR R IN get_products_by_category(1) LOOP
UPDATE products SET CategoryID = NEW.id WHERE id = R.id;
RETURN NEW;
The idea is that I have some Products in database, which have default Category ID as 1. And then, when new Category is added, trigger is fired which update CategoryID
(from freshly added object) for Products with default CategoryID
- maybe it sounds stupid but I am learning triggers with Northwind Database and I had to create task for myself. :)
But I can't save it, because of errors near get_products_by_category(1)
.
Is in PLpgSQL (I am using 9.3 version) any possibility to write something like in Java:
for (Product product: dao.getProductsByCategory(categoryId))
Updated code:
DECLARE
selected_products products[];
product products;
BEGIN
IF TG_TABLE_NAME != 'categories' THEN
RAISE 'This trigger function is for Categories, but was called for %', TG_TABLE_NAME;
END IF;
selected_products := get_products_by_category(1);
FOR product IN selected_products LOOP
UPDATE products SET CategoryID = NEW.id
WHERE id = R.id;
END LOOP;
RETURN NEW;
END;