[英]Export SQL Server data from one database to another
I have a SQL server database of a web application, my requirement is to read 2-3 table data from one source database and insert the data in the destination database. 我有一个Web应用程序的SQL服务器数据库,我的要求是从一个源数据库读取2-3个表数据并将数据插入目标数据库。 My input will be a Name and an ID, based on that I have to read data from the source database and I have to validate whether the similar Name already exists in the destination database. 我的输入将是一个名称和一个ID,基于我必须从源数据库中读取数据,我必须验证目标数据库中是否已存在类似的名称。 I have to do this via a C# windows application or a web application. 我必须通过C#windows应用程序或Web应用程序执行此操作。
So far in my research, people have recommended using SqlBulkCopy or an SSIS package, I tried to transfer one table data using the following code. 到目前为止,在我的研究中,人们建议使用SqlBulkCopy或SSIS包,我尝试使用以下代码传输一个表数据。
using (SqlConnection connSource = new SqlConnection(csSource))
using (SqlCommand cmd = connSource.CreateCommand())
using (SqlBulkCopy bcp = new SqlBulkCopy(csDest))
{
bcp.DestinationTableName = "SomeTable";
cmd.CommandText = "myproc";
cmd.CommandType = CommandType.StoredProcedure;
connSource.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
bcp.WriteToServer(reader);
}
}
The problem I'm facing is that, I have to copy 2 table data, based on table 1, table 2 value like ID(primary key) changes, I have to update this in the SqlDataReader, so in order to get this new ID in the destination database, I have to insert one table data first, then get the ID, then update this ID in my reader object and then do another SqlBulkCopy, this doesn't look like the ideal way to do this, is there any other to do this? 我面临的问题是,我必须复制2个表数据,基于表1,表2的值如ID(主键)更改,我必须在SqlDataReader中更新它,所以为了得到这个新的ID在目标数据库中,我必须首先插入一个表数据,然后获取ID,然后在我的reader对象中更新此ID,然后再执行另一个SqlBulkCopy,这看起来不是理想的方法,有没有其他的去做这个?
On the source SQL instance I would create a linked server referencing destination/target SQL instance and then I would create a stored procedure within source database thus: 在源SQL实例上,我将创建一个引用目标/目标SQL实例的链接服务器,然后我将在源数据库中创建一个存储过程:
USE SourceDatabase
GO
CREATE PROCEDURE dbo.ExportSomething
@param1 DataType1,
@param2 DataType2, ...
AS
BEGIN
INSERT LinkedServer.DestinationDatabase.dbo.TargetTable
SELECT ...
FROM dbo.Table1 INNER JOIN dbo.Table2 ....
WHERE Col1 = @param1 AND/OR ...
END
GO
Then, the final step is to call this stored procedure from client application. 然后,最后一步是从客户端应用程序调用此存储过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.