简体   繁体   English

SQL Server:将所有表复制到新表中

[英]SQL Server: copy all tables into new tables

I am having a problem. 我有问题。

I am trying to create an easy way to make a copy of Table1 to Table2 . 我正在尝试创建一种简单的方法来将Table1复制到Table2 Now I know the Select Into , but in this there is say table 1 through table 100 and I am trying to create a duplicate of all of them. 现在我知道Select Into ,但是在这里有说表1到表100的信息,我正在尝试创建所有表的重复项。 SSIS or SQL is OK. SSIS或SQL可以。

The reason for the copy is say I have 2 tables within a classes database. 复制的原因是说我在class数据库中有2个表。 Alegra 101 and 102, I am trying to create algebra 103 this will work for all of the tables, like Health 101 and 102, assume there are around 100 different classes with a 101 level and a 102 level that need a 103. Alegra 101和102,我正在尝试创建代数103,它适用于所有表,例如Health 101和102,并假设有大约100个不同的类,其中101级和102级需要103。

Not a big fan of dynamic SQL, but you might get away with something like this. 并不是动态SQL的忠实拥护者,但是您可能会避免这样的事情。 Maybe you should give some more insight in to why you might want to "copy" tables - others may have more suitable solutions for you. 也许您应该对为什么要“复制”表提供更多的见解-其他人可能有更适合您的解决方案。

DECLARE @CMD NVARCHAR(4000) = ''

SELECT @CMD = @CMD + 'SELECT * INTO [dbo].[Copy_' + TABLE_NAME + ']' + ' FROM ' + TABLE_SCHEMA + '.' + TABLE_NAME + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES AS t
--  Add your filtering criteria as a WHERE clause

PRINT @CMD  --  to check the code generated

-- EXEC SP_EXECUTESQL @CMD ***UNCOMMENT WHEN READY***

In light of you adding the reason for your needs, I would seriously reconsider my model. 考虑到您添加了需求的原因,我将认真考虑我的模型。 Instead of having n tables, (1 per subject\\class) - a more suitable model would be to keep all homogeneous data in the same table. 而不是具有n个表(每个科目\\每个班级1个表)-一种更合适的模型是将所有同类数据保留在同一表中。

CREATE TABLE Class
(
    ClassID     INT,
    YearOfClass INT,
    ...
    ...
    ClassSubject    VARCHAR(50) -- This could be an FK to a ClassSubject Table
)

Where ClassSubject is populated with values 'Algebra 101', 'Algebra 102' etc... This will save you from having to create tables every time a new subject is added - and having to adjust all your stroed procs accordingly. 在ClassSubject中填充值“ Algebra 101”,“ Algebra 102”等...这将使您不必每次添加新主题时都必须创建表,并且不必相应地调整所有处理的过程。 Amoung many other benefits, aggregations also become simpler. 除了许多其他好处,聚合也变得更加简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM