Trigger to fill table with data from another table

Asked

Viewed 361 times

0

I want to fill a table with the data being placed in another.

CREATE TRIGGER `trg_jogo`AFTER INSERT 
ON `tabela1`
AS 
INSERT INTO `tabela2` SELECT * FROM `tabela1`;

I cannot do the process to copy the data from tabela1 to the tabela2, so whenever a user registers, their data appeared in two tables.

  • What is the database manager: Mysql? Oracle Database? Postgresql? MSSQL?

  • I am using Mysql as BD

1 answer

1

You need to take only what was inserted again, using NEW as an alias.

For example, imagine that "Tabela1" is like this and inserted the record 1:

ID DESCRIPTION
1 Testing

Then use NEW.ID and NEW.DESCRICAO, for example:

CREATE TRIGGER `trg_jogo`AFTER INSERT 
ON `tabela1`
AS 
INSERT INTO `tabela2`(ID, DESCRICAO) VALUES NEW.ID, NEW.DESCRICAO;

The way you’re doing will insert for each new record everything in the table.

Remembering that all these examples are for MySQL

  • CREATE TRIGGER trg_jogo AFTER INSERT
ON tabela1
AS
INSERT INTO tabela2 (user_login, user_pass, user_nicename, user_email) VALUES NEW.user_login, NEW.user_pass, NEW.user_nicename, NEW.user_email; Ele retornou um erro de sintaxe "#1064-You have a syntax error in your SQL next to 'AS INSERT INTO tbl_curso_game (user_login, user_pass, user_nicename, user_email' on line 3 " the table2 is a copy of Tabela1 where the first column is PK

Browser other questions tagged

You are not signed in. Login or sign up in order to post.