将数据从db插入另一个db

时间:2013-03-27 07:30:45

标签: sql sql-server sql-server-2008 sql-insert

我想从旧数据库表中获取值到新数据库表。

旧数据库结构:

表I:Country

  • CountryId
  • 国家或地区名称

新数据库结构

表二:Countries

  • 编号
  • 名称

我使用了以下插入查询,例如

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 Any Country
像那样。

但我需要像

这样的结果
insert into Countries (Id, Name) values (1, 'India')

要实现这一目标,查询是什么?帮助我...

4 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:4)

如果两个数据库都在一台服务器上,您可以这样做:

insert into [db1name].[dbo].[Countries] (Id, Name)
select CountryId, CountryName
from [db2name].[dbo].[Countries]
where _your where clause_

希望这有帮助

答案 3 :(得分: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