如何在SQL Server 2008中使用新名称创建重复的表

Eyl*_*yla 30 sql t-sql sql-server sql-server-2008

如何在SQL Server 2008中创建只有与新名称重复的结构的重复表?

我有45个字段的表,所以我想创建具有相同结构但新名称的新表.

Ava*_*his 50

右键单击SQL Management Studio中的表.

选择脚本...创建到...新查询窗口.

这将生成一个脚本,以在新的查询窗口中重新创建表.

将脚本中的表名更改为您希望命名新表的名称.

执行脚本.


Con*_*rix 37

SELECT * 
INTO target
FROM  source
WHERE 1 = 2
Run Code Online (Sandbox Code Playgroud)

  • @AdilMalik要求仅复制表结构的问题.因此1 = 2会阻止复制任何数据. (12认同)
  • 这只会捕获一些结构.相同的列名,数据类型和可空设置.但其他一切都将落在后面.在我的脑海中留下的东西将包括PK,UK,FK和Check约束,身份属性和计算列.这取决于OP需要多少结构,以满足OP的需求. (9认同)

小智 10

  SELECT * INTO newtable FROM oldtable where 1=2
Run Code Online (Sandbox Code Playgroud)

Where 1=2 当您需要复制表的完整结构而不复制数据时使用。

 SELECT * INTO newtable FROM oldtable 
Run Code Online (Sandbox Code Playgroud)

要创建包含数据的表,您可以使用此语句。


小智 7

从现有表创建新表:(将 Old_Table 中的所有行复制到 de New_Table):

SELECT * INTO New_table FROM  Old_Table
Run Code Online (Sandbox Code Playgroud)

要将数据从一个表复制到另一个表(当您已经创建它们时):

Insert into Table_Name2 select top 1 * from Table_Name1
Run Code Online (Sandbox Code Playgroud)

请记住删除top 1参数并在需要时应用相关的 where 子句Select


Rou*_*man 6

Here, I will show you 2 different implementation:

First:

If you just need to create a duplicate table then just run the command:

SELECT top 0 * INTO [dbo].[DuplicateTable]
FROM [dbo].[MainTable]
Run Code Online (Sandbox Code Playgroud)

Of course, it doesn't work completely. constraints don't get copied, nor do primary keys, or default values. The command only creates a new table with the same column structure and if you want to insert data into the new table.

Second (recommended):

But If you want to duplicate the table with all its constraints & keys follows this below steps:

  1. Open the database in SQL Management Studio.
  2. Right-click on the table that you want to duplicate.
  3. Select Script Table as -> Create to -> New Query Editor Window. This will generate a script to recreate the table in a new query window.
  4. Change the table name and relative keys & constraints in the script.
  5. Execute the script.