从一个数据库向另一个数据库插入数据。

7

我希望从旧的数据库表中取出值并插入到新的数据库表中。

旧数据库结构:

表I: Country

  • CountryId
  • CountryName

新数据库结构:

表II: Countries

  • Id
  • Name

我使用了下面的插入查询语句,如下所示:

select 'insert into Countries (Id, Name) select ', countryid, countryname from Country

但是我得到的结果是这样的:

  • insert into Countries(Id,Name) select 1 India
  • insert into Countries(Id,Name) select 2 任何国家

像这样。

但我需要的结果是这样的:

insert into Countries (Id, Name) values (1, 'India')

为了实现这个目标,需要什么查询?请帮我...
4个回答

11

如果需要传输大量数据和多个表格,我建议使用 SQL Server Management Studio 提供的 Import/Export 向导。

http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

编辑: 但是,如果数据量不大且两个系统未连接,并且需要生成脚本来传输数据,则查询应如下所示:

SELECT 'INSERT INTO Countries (Id, Name) VALUES (' + CAST(countryid AS VARCHAR(50)) + ', ''' + countryname + ''')' from Country

哇,我以前从未尝试过导入/导出向导。谢谢@NenadZivkovic先生。 - Jeancarlo Fontalvo

6
如果两个数据库在同一服务器上,您只需像这样操作:
insert into [db1name].[dbo].[Countries] (Id, Name)
select CountryId, CountryName
from [db2name].[dbo].[Countries]
where _your where clause_

希望这能帮到您。

5

使用简单的INSERT语句(database_name.[schema_name].table)

INSERT [NewDB].[your_schema].[Countries](Id,Name)
SELECT CountryId, CountryName
FROM [OldDB].[your_schema].[Country]

3
说实话,我并不是很理解你所写的查询内容。你是想从查询中构建字符串,然后再次传递到数据库中吗?
你可以在一个查询中将一个数据库中的值直接传递到另一个数据库中:
/*
    maybe you need to switch off identity on your target table
    to get your original id values into the target table like this:
    (without comment ofc ;))
*/
--SET IDENTITY_INSERT TargetDatabase.dbo.Countries ON

INSERT INTO TargetDatabase.dbo.Countries (Id, Name)
    SELECT
            CountryId, CountryName
        FROM SourceDatabase.dbo.Country

--SET IDENTITY_INSERT TargetDatabase.dbo.Countries OFF

或者您可以使用临时表,在检索原始值后切换数据库连接。

USE SourceDatabase

DECLARE @TempTable TABLE (CountryId INT PRIMARY KEY, CountryName NVARCHAR(MAX))

INSERT INTO @TempTable (CountryId, CountryName)
    SELECT
            CountryId, CountryName
        FROM Country

USE TargetDatabase

/*
    maybe you need to switch off identity on your target table
    to get your original id values into the target table like this:
    (without comment ofc ;))
*/
--SET IDENTITY_INSERT Countries ON

INSERT INTO Countries (Id, Name)
    SELECT
            CountryId, CountryName
        FROM @TempTable

--SET IDENTITY_INSERT Countries OFF

编辑:正如先前的帖子提到的,要使其工作,您需要将两个数据库放在同一台服务器上,因为您没有提到这一点,所以我只是假设了这种情况? :D


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接