1

--Problem is: i have more companies and i want to make id_shutter "autoincrement" from 1 for each company (id_company and id_shutter are composite PK)

 CREATE FUNCTION insert_shutter() RETURNS TRIGGER AS $insert_shutter$
BEGIN
    IF exists(select 1 from shutter where id_company=new.id_company) then
    SELECT MAX(id_shutter) INTO new.id_shutter FROM shutter where id_company=new.id_company;
    new.id_shutter:=id_shutter+1;
    ELSE
    new.id_shutter=1;
    end if;
        RETURN NEW;

END;
$insert_shutter$ LANGUAGE plpgsql;

CREATE TRIGGER insert_shutter 
    BEFORE INSERT ON shutter
    FOR EACH ROW
    EXECUTE PROCEDURE insert_shutter();

2 Answers 2

2

sorry i found out, i cant use: new.id_shutter:=id_shutter+1; i made SELECT MAX(id_shutter)+1 INTO new.id_shutter FROM shutter where id_company=new.id_company;

Sign up to request clarification or add additional context in comments.

Comments

0

Occasionally this is necessary. But really, it is much easier to add a serial column to the table (let's call it ShutterId) and then do the calculation when you retrieve the data:

select s.*, row_number() over (partition by company order by id) as CompanyShutterSequence
from shutter s;

Also, calling something an id that will take on duplicated values is misleading.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.