sql - PostgreSQL copy to a new table with one extra column. How?
问题描述
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! :)
解决方案
只需像这样使用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
推荐阅读
- pyspark - 根据 pyspark 中复杂 JSON 的 1 个字段中存在的关键字过滤行
- pytorch - 这个 LSTM 循环代码会破坏 PyTorch 中的计算图吗?
- google-cloud-functions - 将 Google Cloud Functions 中的 Webhook 与 Dialogflow CX 结合使用
- c++ - 错误 E0304;函数 std::string.insert(),显示为具有 9 个重载的重载函数 VS2019
- wpf - C# WPF 如果两个背景颜色不同的 Rectangle 完全重叠,就会出现下面这个 Rectangele 的边框
- c - 计算 C 中两个标签之间的代码大小(操作码字节数)
- sql - 在 UiPath 中执行 sql 查询以从雪花中提取数据
- javascript - NuxtJS 如何使用 emit 重新加载 asyncData
- sql - PostgreSQL 选择方法,如 excel
- angular - Angular's ngOnInit vs constructor. What to place In each?