SQL Server:如何将多个数据库合并到一个数据库中?

时间:2017-01-11 00:37:12

标签: sql sql-server

enter image description here

从我的原始数据库中,我对表中的列进行了一些表的更改,我想将它们合并到一个数据库中。新数据库只需添加一些表,旧表添加一些列。

如何将多个数据库合并到一个数据库中?

SQL示例:

CREATE TABLE [dbo].[Item]
(
    [ItemID] [nchar](10) NOT NULL,
    [Money] [bigint] NOT NULL,
    [ItemName] [bigint] NOT NULL,
    [MoneyType] [bigint] NOT NULL,

    CONSTRAINT [PK_Item] 
        PRIMARY KEY CLUSTERED ([ItemID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Account]
(
    [Index] [int] IDENTITY(1,1) NOT NULL,
    [AccountID] [nchar](10) NOT NULL,
    [AccountName] [int] NOT NULL,
    [ItemList] [int] NOT NULL,
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Money]
(
    [AccountID] [nchar](10) NOT NULL,
    [Money] [bigint] NOT NULL,
    [MoneyType] [bigint] NOT NULL,

    CONSTRAINT [PK_Money] 
        PRIMARY KEY CLUSTERED ([AccountID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO

- > Nick.McDermaid:使用Visual Studio中的模式比较工具(各种免费版本),它将创建一个更改脚本!

1 个答案:

答案 0 :(得分:0)

如果Account表尚不存在,它会将它们组合到DBCombined.Account上:SELECT INTO代码创建目标表。然后,您需要添加原始表中的任何索引。此外,“SELECT *”应该真正打破,列出每个字段,因为如果你有一个ID字段,它将包含重复项。最好在插入期间关闭ID,然后返回并添加标识列。

USE DBCombined
GO

SELECT *
INTO Account
FROM (
    SELECT *
    FROM DB1.dbo.Account
    UNION ALL
    SELECT * 
    FROM DB2.dbo.Account
    ) Acct