6.9.08

Copy table structure in SQL Server

Copy only structure with out data from SQL Server table:
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)
Way to copy the structure of the table:
Using below query, we can copy the structure of the table without any data.

SELECT * INTO NewTable FROM Table1 WHERE 1=2
SQL Server will first create the table and insert the data. Since, our where clause fails due to the condition,
only structure will be created without any data.

SELECT count(*) FROM NewTable
The output will be 0
Happy Learning!!!
Regards,
Venkatesan Prabu .J

1 comment:

  1. It can be done even easier:

    Select *
    INTO New_Table
    FROM Existing_Table
    WHERE Some_Field=Something_that_newer_existed

    ReplyDelete