2
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;

用户和历史是一对一的关系。在创建新用户之前,我如何在历史记录表中插入新记录。

4

1 回答 1

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

并将触发语句写为

CREATE TRIGGER user_hist
BEFORE INSERT ON users
FOR EACH ROW EXECUTE function  recordcreatetime() ;
于 2012-10-29T12:15:28.377 回答