I'm having trouble passing data from one table to another: Example:
Table 1 --- > Table 2 --- > delete all information from Table 1
I'm creating the project in VB.NET and using SQL
I'm having trouble passing data from one table to another: Example:
Table 1 --- > Table 2 --- > delete all information from Table 1
I'm creating the project in VB.NET and using SQL
If the second table already exists use INSERT INTO SELECT
If the two tables have the same fields:
INSERT INTO table2
SELECT * FROM table1;
If only a few fields are common, you must enter these fields:
INSERT INTO table2
(column_name1, column_name2, ...)
SELECT column_name1, column_name2, ...
FROM table1;
Note: Field names may be different, they must be of the same type. They will be filled according to the order in which they are declared.
In both cases the WHERE clause can be used:
INSERT INTO table2
(column_name1, column_name2, ...)
SELECT column_name1, column_name2, ...
FROM table1
WHERE column_name1 = "a qualquer coisa";
To delete the table use:
DROP TABLE tabela1
Basically speaking:
Create a tabela_2
table based on tabela_1
:
CREATE TABLE tabela_2 AS SELECT * FROM tabela_1
Delete the copied table.
DROP TABLE tabela_1
Note : chaves-primárias
and chaves-estrangeiras
are not replicated in tabela_2
, if they exist in tabela_1
. Not even AUTO_INCREMENT
is copied.
It's important to post here that I found a better and better way for you to not be able to copy primary and foreign keys.
There is a way to do this through LIKE
. Instead of just copying the table, ignoring the keys, it literally copies the table, with keys and more.
See:
CREATE TABLE tabela_3 LIKE tabela_1;
INSERT INTO tabela_3 SELECT * FROM tabela_1;
In this case, we execute two queries. It is not a disadvantage, since you will have the keys
f% of the original table copied.