I need to make trigger, which will delete related rows in related table. Yes, I know about ON DELETE CASCADE, but the thing is I need to do it using trigger. I google it for several hours, but don't find solution for Postgesql. I use postgresql 9.4, pgAdmin III.
I have the following tables:
CREATE TABLE "Customer"
(
"Id" serial NOT NULL,
"ContactPerson" text NOT NULL,
"Address" text NOT NULL,
"PhoneNumber" "PhoneNumber" NOT NULL,
CONSTRAINT "CustomerId (PK)" PRIMARY KEY ("Id")
)
WITH (
OIDS=FALSE
);
CREATE TABLE "Order"
(
"Id" serial NOT NULL,
"OrderDate" date NOT NULL DEFAULT ('now'::text)::date,
"Amount" integer NOT NULL DEFAULT 1,
"CustomerId" integer NOT NULL,
"GoodId" integer NOT NULL,
CONSTRAINT "OrderId (PK)" PRIMARY KEY ("Id"),
CONSTRAINT "CustomerId (FK)" FOREIGN KEY ("CustomerId")
REFERENCES "Customer" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT "GoodId (FK)" FOREIGN KEY ("GoodId")
REFERENCES "Good" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT "AmountCheck" CHECK ("Amount" > 0),
CONSTRAINT "OrderDateCheck" CHECK ("OrderDate" <= 'now'::text::date)
)
WITH (
OIDS=FALSE
);
I create trigger using this query:
CREATE FUNCTION DeleteCustomerWithOrders() RETURNS trigger AS $DeleteCustomerWithOrders$
BEGIN
DELETE FROM "Order"
WHERE "Order"."CustomerId" = (SELECT "Id" FROM "Customer");
RETURN "Customer";
END;
$DeleteCustomerWithOrders$ LANGUAGE plpgsql;
CREATE TRIGGER DeleteCustomerWithOrders BEFORE DELETE ON "Customer"
EXECUTE PROCEDURE DeleteCustomerWithOrders();
The query runs well, but then I try to delete row from Customer, it gets an error:
(column "Customer" does not exists)
There is only examples of ON INSERT or UPDATE triggers in documentation, there they use RETURN NEW. Also I saw using OLD in sql-server. Nothing of it helps in my case. Also there may be errors in WHERE.
UPDATE
Thanks to Patrick. This solves first problem, but causes another one.
Error: record old does not assigned value. Detail: for not assigned record cortege structure is not defined.


lc_messages=English)lc_messages=EnglishI should write it in script or in pgAdmin settings? Sorry, don't understand, what do you mean "dreaded quoted identifiers", my function name?