I have two tables in postgres, I want to create a function that doesn’t have more than 2 loans in the lending table with the same person id. example: in the loan table I cannot have 3 loans that are from the same person, that is, we loan with the same person's id.
I need to do this using a function, I put what I was trying to do but it didn't work
CREATE TABLE person (
name_person varchar (100) ,
id_person varchar(14) primary key
)
CREATE TABLE lending(
id_lending primary key (100) ,
id_publication (14) FK,
id_person fk REFERENCES id_person (person)
CREATE OR REPLACE FUNCTION check_numlending()
RETURNS trigger AS
$BODY$
BEGIN
IF( select * from lending
inner join person
on person.id_person = lending.id_person > 2 ) THEN
RAISE EXCEPTION 'ERROR';
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
-- Trigger
CREATE TRIGGER
trg_check_num_lending
BEFORE INSERT OR UPDATE ON
lendingFOR EACH ROW EXECUTE PROCEDURE check_numlending();
NEW.id_person = person.id_person > 2supposed to do? If you want to verify some condition on the existing table data, you need to execute aSELECTinside the functionSELECT COUNT(*)... You would be well advised to learn the basics of SQL first; otherwise, you're going to have a hard time writing DB procedures and functions