CREATE TABLE users
(
 id integer NOT NULL DEFAULT nextval('userseq'::regclass)
 ........
)

CREATE TABLE History
(
 userid integer,
 createdat timestamp with time zone
)

CREATE OR REPLACE FUNCTION recordcreatetime()
      RETURNS trigger AS
        $BODY$
        BEGIN
                NEW.createdAt = NOW();
                RETURN NEW;
        END;
        $BODY$
          LANGUAGE plpgsql VOLATILE
          COST 100;

User and History has one-one relationship. How i can insert new record in History table before creating new user.

share|improve this question

75% accept rate
feedback

1 Answer

up vote 3 down vote accepted
CREATE OR REPLACE FUNCTION recordcreatetime()
  RETURNS trigger 
language plpgsql
AS $$
DECLARE
BEGIN
INSERT INTO History values(new.id,NOW() );
 RETURN NEW;
END;
$$;

and write trigger statement as

CREATE TRIGGER user_hist
BEFORE INSERT ON users
FOR EACH ROW EXECUTE function  recordcreatetime() ;
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.