SQL Server How do I create a table based on another table [duplicate]

sz81bmfz  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(142)

This question already has answers here:

Try to create a table from Select - SqL Server 2008 throws error (4 answers)
Closed 10 years ago.

I want to create a table based on the definition of another table.

I'm coming from oracle and I'd normally do this:

  1. CREATE TABLE schema.newtable AS SELECT * FROM schema.oldtable;

I can't seem to be able to do this in SQL Server 2008.

jobtbby3

jobtbby31#

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in data warehouse technologies (like APS / dedicated pools ). In SQL Server you can use this query to create an empty table:

  1. SELECT * INTO schema.newtable
  2. FROM schema.oldtable
  3. WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

If you don't want to keep the IDENTITY property, you can just convert it first to its original data type:

  1. SELECT IdentityColumn = CONVERT(int/bigint, IdentityColumn),
  2. ...other columns...
cuxqih21

cuxqih212#

  1. select * into newtable from oldtable

相关问题