使用Forloop将数据导入一个表到另一个表

问题描述:

大家晚上好

我有访问数据库.
在数据库上有两个表.然后我想将数据从一个表导入到另一个表

我正在编写此代码,但发生了错误


Good Evening all of us

I have the access database.
On the database there are two tables. Then I want to import data from one table to another table

I am writing this code but it has taken error


foreach (DataRow dr in sourceTable.Rows)
{
    destinationTable.ImportRow(dr);
}


////////////////////


foreach (DataRow dr in sourceTable.Rows)
{
    r = destinationTable.NewRow;
    r("Name") = dr["Name"];
    r("City") = dr["City"];
    r("Cost") = dr["Cost"];
    destinationTable.Rows.Add(r);
}




所以你能给我关于循环条件的指导吗?

[edit]添加了C#代码的预标签.拼写错误已纠正-PES [/edit]




so can u give me guidance in for loop condition

[edit]pre tag for C# code added. Spelling mistakes corrected - PES[/edit]

在源表中,如果进行了任何修改,则数据行的RowState 将为Modified状态.因此,无法将导入行的RowState设置为Added状态.因此,您必须首先在源表上调用AcceptChanges 方法,然后按如下所示导入行

In the source table, if any modification is done the RowState of the data row will be Modified state. Due to this the RowState of the imported row cannot be set to Added state. Hence, you have to first call AcceptChanges method on the source table and then import the rows as follows

sourceTable.AcceptChanges();
foreach (DataRow dr in sourceTable.Rows)
{
    destinationTable.ImportRow(dr);
    //Set the row state of the newly row added row to Added state.
    destinationTable.Rows(destinationTable.Rows.Count - 1).SetAdded();
}



您可以接受并投票解决问题的解决方案之一,否则请发布您的查询.



You may accept and vote one of the solutions which solved your problem, otherwise please post your queries.


为什么不尝试使用Merge()方法.没有循环,我猜你在表之间没有很大的架构差异.
Why don''t you try with Merge() method. No loops and I guess you don''t have great schema difference between tables.
//
destinationTable.Merge(sourcetable);
//


同一表中的两个表数据库..um
如何在访问中运行SQL脚本?

two tables in the same database..um
how about running SQL-Script in access?

string sqlscript = @"
Insert into destTable(FieldA,FieldB,FieldC)
Select FieldA,FieldB,FieldD
from SourceTable";

cmd.CommandText=sqlscript;
cmd.ExecuteNonQuery();



http://office.microsoft.com/en-us/access- help/insert-into-statement-HA001231488.aspx [ ^ ]



http://office.microsoft.com/en-us/access-help/insert-into-statement-HA001231488.aspx[^]