المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Replace two table's items with eachother in SQL



C# Programming
03-17-2010, 04:54 AM
Hello, As you may see below, I'm trying to replace the contents of two tables with eachother from a Windows form but it doesn't work. It may not be the best practice I know and waiting for your valuable comments

SqlConnection conn = new SqlConnection();
SqlDataAdapter sqlAdaptorSource;
SqlDataAdapter sqlAdaptorTarget;
SqlCommandBuilder sqlCommandSource;
SqlCommandBuilder sqlCommandTarget;
DataTable dtSource = new DataTable();
DataTable dtTarget = new DataTable();
DataTable dtBackup = new DataTable();public void changeTables()
{
conn.ConnectionString = @"Data Source=" + System.Environment.MachineName + @"\SQLEXPRESS;Initial Catalog=Kafe;Integrated Security=SSPI;";
conn.Open();

sqlAdaptorSource = new SqlDataAdapter("Select * From Table1", conn);
sqlAdaptorTarget = new SqlDataAdapter("Select * From Table2", conn);

sqlCommandSource = new SqlCommandBuilder(sqlAdaptorSource);
sqlCommandTarget = new SqlCommandBuilder(sqlAdaptorTarget);

sqlAdaptorSource.Fill(dtSource);
sqlAdaptorTarget.Fill(dtTarget);

//Backup the target table first
dtBackup = dtTarget;

// Move the Source to Target
dtTarget = dtSource;
sqlAdaptorTarget.Update(dtTarget);

//Then move the Target to Source
dtSource = dtTarget;
sqlAdaptorSource.Update(dtSource);

//Dispose all
dtSource.Clear();
dtTarget.Clear();
dtBackup.Clear();
dtSource.Dispose();
dtTarget.Dispose();
dtBackup.Dispose();
conn.Close();
conn.Dispose();
}