Wednesday, February 25, 2009

SQL - Copying the structure of a table

Gurus,

There are two ways of copying the structure of an existing table in SQL Server. Either we can copy the structure aong with existing data or structure of table alone. Please find below the sample for both:

Copying table structure with existing data:
SELECT *INTO new_table_name
FROM old_table_name

This query will create a new table new_table_name with data present in the table old_table_name. We can use this technique to take a backup of existing table in our database.

Copying table structure without data:
At times, we may require to create a table with the existing table structure. But, we may not require to copy the existing data into that. We can use the following snippet in that case:

SELECT *INTO new_table_name
FROM old_table_name
WHERE 1>2

This query will create table new_table_name without any data from the table old_table_name because of the WHERE condition.

Gurus, I hope this might be helpful for you. Will try to add more stuffs in future.

Signing off with cheers,
Harikaran.S

No comments:

Post a Comment