简体   繁体   中英

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. 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. I have to do this via a C# windows application or a web application.

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.

        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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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