In our database world, we used to face this situation frequently. You will be given a table and requested
to copy those data into another table. Let's see how to achieve this scenario,
Am creating a table name Table1,
CREATE TABLE Table1(id int primary key,nam varchar(10))
I am creating the second table Table2.
CREATE TABLE Table2(id1 int primary key, nam varchar(10))
Now, am trying to link these two tables using a column named id in first table with id in the second table.
ALTER TABLE Table2
ADD FOREIGN KEY (ID1) REFERENCES
Table1(ID)
First way of copying source table data:
In this case, a new table can be created similar to the structure of the source table
and after wards, an insert statement can be fired
CREATE TABLE NewTable1(id int primary key,nam varchar(10))
INSERT INTO NewTable1(id,nam) SELECT id,nam FROM Table1
Second way to copy data from a table:
In this case, a table of similar structure will be created and data will be inserted into the table.
The new table structure resembles the old table structure.
SELECT * INTO NewTable2 FROM Table1
Oops!!! In the second case, I am doubting about the constraints. Whether the constraints is copied in the new table. No, its not the case.
Only the structure and the data will get copied to the new table and we need to create our constraints on the new table.
Lets check it by executing the below query,
SP_HELP Table1-- [sp_help will provide the details about the system object]
Let's check with the new table created.
SP_HELP NewTable2
Happy Learning!!!
Regards,
Venkatesan Prabu .J
No comments:
Post a Comment