[英]DataAdapter : if row already exist, then update, else insert
我有一個帶有本地SQL CE數據庫的Windows Mobile PPC,我試圖在連接時將其復制到遠程SQL Server數據庫。 我不能使用批量復制或任何其他“自動化”方法,因為該平台已經過時並且SQL CE受到限制。
我在這里采用了一個解決方案,但是我有點迷茫,因為該過程在目標數據庫為空時運行良好,但是在它具有預先存在的數據時會失敗(主鍵錯誤)。 因此,DataAdapter可能僅進行插入,而不能進行更新。
這是我的代碼:
private void StockSqlBuilder()
{
DataSet SqlCeDataset = new DataSet("source");
DataSet SqlDataset = new DataSet("destination");
try
{
_conn.Open();
// Pull data from local database SQLCE
using (SqlCeDataAdapter sourceDA = new SqlCeDataAdapter("SELECT * FROM stock", _conn))
{
MessageBox.Show("Pull Stock from CE");
sourceDA.Fill(SqlCeDataset, "stock");
}
_conn.Close();
_remoteConn.Open();
// Connect to SQL Server database to push data
using (SqlDataAdapter destinationDA = new SqlDataAdapter("SELECT * FROM stock", _remoteConn))
{
// Get table of remote SQL Server, then loop through all rows of SQLCE and add them to dataset
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(destinationDA);
destinationDA.Fill(SqlDataset, "stock");
foreach (DataRow row in SqlCeDataset.Tables["stock"].Rows)
{
SqlDataset.Tables[0].NewRow();
SqlDataset.Tables[0].Rows.Add(row.ItemArray);
}
destinationDA.Update(SqlDataset, "stock");
}
_remoteConn.Close();
}
catch (SqlException Sqlex)
{
MessageBox.Show(Sqlex.Message);
this.returnStatus = false;
}
catch (SqlCeException SqlCEex)
{
MessageBox.Show(SqlCEex.Message);
this.returnStatus = false;
}
}
另外,如果您對我的項目有雙向SQL同步的其他解決方案,我會不勝枚舉,但我嘗試了很多不同的方法。
使用臨時表進行合並查詢並比較選擇性更新的日期,可獲得良好的結果:
string mergeQuery = @"--Synchronize the target table with refreshed data from source table
MERGE dbo.stock AS TARGET
USING dbo.stock_sync AS SOURCE
ON (TARGET.product_id = SOURCE.product_id)
--When records are matched, update the records if there is any change
WHEN MATCHED AND SOURCE.date_stock > TARGET.date_stock THEN
UPDATE SET TARGET.spot= SOURCE.spot,
TARGET.date_stock = SOURCE.date_stock,
TARGET.loading_id = SOURCE.loading_id
--When no records are matched, insert the incoming records from source table to target table
WHEN NOT MATCHED BY TARGET THEN
INSERT (spot, product_id, date_stock, loading_id)
VALUES (SOURCE.spot, SOURCE.product_id, SOURCE.date_stock, SOURCE.loading_id);
SELECT * FROM dbo.stock;";
// Merge the two tables by matching code_barre row
SqlCommand mergeSql = new SqlCommand(mergeQuery, _remoteConn);
int rowsAffected = mergeSql.ExecuteNonQuery();
MessageBox.Show("Données affectées : " + rowsAffected);
// Clean the temporary source table
SqlCommand recleanSql = new SqlCommand("TRUNCATE TABLE dbo.stock_sync", _remoteConn);
recleanSql.ExecuteNonQuery();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.