tags:

views:

453

answers:

7

I need a query to create a table which is the exact replica but with different table name and without any data from the source table using a sql query!

+2  A: 
  • SQL Server Management Studio
  • Object Explorer
  • Connect -> Your server
  • Databases -> Choose Database
  • Tables
  • Right Click Your Table
  • Script Table as -> Create To -> New Query Editor Window
Tom Ritter
A: 

This can help you:

CREATE TABLE foo AS SELECT...

Read more here

Artem Barger
isnt create table as select an Oracle-ism ?
ShoeLace
you can find it in reference I've posted above. many of RDBS has this feature.
Artem Barger
+2  A: 

For MySQL, you can call SHOW CREATE TABLE table_name;

It will display a CREATE TABLE query. Simply change the table name in that query and you're good to go.

http://dev.mysql.com/doc/refman/5.1/en/show-create-table.html

Jacob Lauzier
+2  A: 

If you use Postgresql:

CREATE TABLE LIKE table_name

http://www.postgresql.org/docs/8.1/static/sql-createtable.html

DaNieL
+7  A: 

You can try this

SELECT * INTO Table_Copy
FROM Table
where 1=2

It will create a empty table with the same structure.

Jonathan
I don't think you'll get FK's, Indexes, or the like, but if you just need a quick-n-dirty, this will do the trick.
Tom Ritter
A: 
select * into newtablename from sourcetablename
go
truncate newtablename
go

That will result in an exact copy but it also copies the data at first which you remove with the truncate statement.

Peter
+1  A: 

Jonathan has it (upvoted), and you should probably go with that because it's more portable. I normally use something similar:

SELECT TOP 0 * INTO [New_Table] FROM [Old_Table]

I think this better expresses what you're doing, but I like Jonathan's because 'TOP 0' is SQL Server specific, and so his is more portable.

Joel Coehoorn