我想通过使用以下条件将数据从一个数据库批量复制或更新到另一个数据库:
这是我的代码,在这里我从本地数据库获取数据,然后将其BulkCopy复制到中央数据库。如何在代码中添加这些条件?
string localConnectionString = GetLocalConnection();
string sqlConnectionStringNP01 = GetNP01Connection();
using (DataTable dt = new DataTable())
{
using (SqlConnection conn = new SqlConnection(localConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
// Getting Local DB Data
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
// Copying to Central Database
using (SqlConnection conn2 = new SqlConnection(sqlConnectionStringNP01))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
// I want to add the code to do the checking here if possible
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
MessageBox.Show("Data successfully transfered to Central Database", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
答案 0 :(得分:0)
正如@Jeroen在评论中所写,SqlBulkCopy
只能插入。
但是,您可以插入一个临时表并创建一个SQL,以在目标表中执行MERGE
语句。
免责声明:我是项目Bulk Operations
的所有者该库不是免费的,但提供您要寻找的BulkMerge
选项。
using (BulkOperation copy = new BulkOperation(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BatchTimeout = 240;
copy.BulkMerge(dt);
MessageBox.Show("Data successfully transfered to Central Database", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
答案 1 :(得分:-1)
您正在使用到Sql Server的特定连接类,因此您的代码不需要与其他RDBMS一起使用。 我建议您使用存储过程来添加封装在事务中的所有条件:
DECLARE
@CrLf nvarchar(2),
@Exception nvarchar(4000)
SET @CrLf=char(13) + char(10)
BEGIN TRY
BEGIN TRAN YOUR_TRAN
--YOUR CODE
COMMIT TRAN YOUR_TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN YOUR_TRAN
SELECT
@Exception='Error number: ' + CAST(COALESCE(ERROR_NUMBER(), 0) as nvarchar) + @CrLf +
'Procedure name: ' + COALESCE(ERROR_PROCEDURE(), 'N\A') + @CrLf +
'Error row: ' + CAST(COALESCE(ERROR_LINE(), 0) as nvarchar) + @CrLf +
'Error message: ' + COALESCE(ERROR_MESSAGE(), 'N\A')
PRINT(@Exception)
RAISERROR (@Exception, -- Message text.
16, -- Severity.
1 -- State.
);
END CATCH