日期:2014-05-18  浏览次数:20877 次

ds插入
將查詢的結果放入ds.怎麼將它插入到加另一張表?謝謝

------解决方案--------------------
我想,搂主应该是这个意思吧(不关心具体表结构,但是源表与目标表结构必须一致,或者,原adapter的结构与目标adapter的结构一致):
C# code

static void Main(string[] args)
        {
            SqlConnection con = new SqlConnection("connection string ");
            SqlDataAdapter adapter = new SqlDataAdapter("select top 2 * from dst1",con); //从表1中查询
            DataSet ds = new DataSet();
            adapter.Fill(ds,"sourceTable");
            DataRowCollection rowCollection = ds.Tables[0].Rows; //行集合
            
            SqlDataAdapter adapter2 = new SqlDataAdapter("select * from dst2",con); //从表2中查询
            DataSet ds2 = new DataSet();
            adapter2.Fill(ds2,"targetTable");

            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(adapter2);
            adapter2.InsertCommand = cmdBuilder.GetInsertCommand();


            foreach (DataRow dr in rowCollection)
            {
                DataRow newRow = ds2.Tables[0].NewRow();
                newRow.ItemArray = (Object[])dr.ItemArray.Clone();
                ds2.Tables[0].Rows.Add(newRow);
            }
            adapter2.Update(ds2, "targetTable");

            Console.ReadLine();
        }