2

I am trying to make a forum database and in this database I have a trigger. After the Insert it should copy the values of the other table into the new one, but should also make a new column showing the actual registerdate of the user. Here is the trigger code:

Create OR REPLACE FUNCTION insertUser() RETURNS TRIGGER AS $insertUser$

BEGIN 

    INSERT INTO public.freshlyinserted(user_id, username, bday, gender, uemail, pasword)
    VALUES (NEW.user_id, NEW.username, NEW.bday, NEW.gender, NEW.uemail, NEW.pasword, NEW.registerdate);

RETURN NEW;
END;
$insertUser$ LANGUAGE plpgsql;

CREATE TRIGGER moveUserToInserted
AFTER INSERT ON forumusers
FOR EACH ROW EXECUTE PROCEDURE insertUser();

When i try this, it tells me this:

ERROR Record "new" has no field "registerdate" CONTEXT: SQL statement "INSERT INTO public.freshlyinserted(user_id, username, bday, gender, uemail, pasword) VALUES (NEW.user_id, NEW.username, NEW.bday, NEW.gender, NEW.uemail, NEW.pasword, NEW.registerdate)". PL/pgSQL function insertuser() row 2 for SQL statement

The forumuser table doesn't have the "registerdate" column...but I really would like it for the new Table withe the actual date(i dont know how to do it tho). I would be happy, if I get help with this. I will post any more needed code! Btw. Without the registerdate, it works...but then the table would make no sense for me XD

Thanks! :)

4

3 回答 3

1

只需像这样使用current_date

Create OR REPLACE FUNCTION insertUser() RETURNS TRIGGER AS $insertUser$

BEGIN 

    INSERT INTO public.freshlyinserted(user_id, username, bday, gender, uemail, pasword)
    VALUES (NEW.user_id, NEW.username, NEW.bday, NEW.gender, NEW.uemail, NEW.pasword, current_date);

RETURN NEW;
END;
$insertUser$ LANGUAGE plpgsql;

CREATE TRIGGER moveUserToInserted
AFTER INSERT ON forumusers
FOR EACH ROW EXECUTE PROCEDURE insertUser();

您还可以使用current_timestamp

在这里您可以看到使用它们时它们会返回或保存什么:https ://dbfiddle.uk/?rdbms=postgres_12&fiddle=57bae2ba351bac477724aa5551c73ee2

于 2020-01-26T16:17:18.573 回答
0

不需要更改触发器,您可以在创建/更改表时使用DEFAULT子句。

ALTER TABLE public.freshlyinserted
    ALTER COLUMN registerdate
        SET DEFAULT now();
于 2020-01-26T22:03:58.747 回答
0

如果我理解正确,只需将 NEW.registerdate 替换为您可以使用函数 NOW() 的当前日期

于 2020-01-26T16:11:45.507 回答