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

关于insert语句插入错行的问题
有a,b两个表,还有一个a,b的字段对应表,从将a表的字段名存到一个数组中,读取对应字段表,然后利用循环语句,利用insert语句在b表中抓取数据,每次抓取一个字段,为什么会出现错行的问题,该怎么解决,用update,但是我update的where条件不会写啊
C# code

private void button5_Click(object sender, EventArgs e)
        {
            string strSrc = "Server=LIUKAI-THINK;Integrated security=SSPI;database=CkMonitor";
            using (SqlConnection thisConnection = new SqlConnection(strSrc))
            {
                thisConnection.Open();
                SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT * FROM SelectedFields", thisConnection);//读取对应关系表
                DataSet thisSet = new DataSet();
                thisAdapter.Fill(thisSet, "SelectedFields");
                DataTable tbl1 = thisSet.Tables[0];
                int rowCount = tbl1.Rows.Count;
                int columnCount = tbl1.Columns.Count;
                string[]OriginalTableName=new string[rowCount];//原始数据库表名
                string[]TargetTableName=new string[rowCount];//目标数据库表名
                for (int i = 0; i < rowCount; i++)
                {
                    OriginalTableName[i]=tbl1.Rows[i][0].ToString();
                    TargetTableName[i]=tbl1.Rows[i][1].ToString();
                }    
                for (int i = 0; i < rowCount; i++)
                {
                    int count=0;
                    for(int j=0;j<columnCount;j++)
                    {
                        if(DBNull.Value!=tbl1.Rows[i][j])
                        {
                            count++;
                        }
                    }
                    //读取目标数据库的字段名并存在一个数组Target里
                    ArrayList Target = new ArrayList();
                    string strField = "SELECT c.name FROM syscolumns AS c inner join sysobjects d on c.id=d.id and d.xtype='U' and d.name<>'dtproperties' where d.name='"+TargetTableName[i]+"'";
                    SqlCommand thisCommandField = thisConnection.CreateCommand();
                    thisCommandField.CommandText =strField;
                    SqlDataReader thisReaderTarget = thisCommandField.ExecuteReader();       
                    while (thisReaderTarget.Read())
                    {
                        Target.Add(thisReaderTarget["name"]);
                    }
                    
                    thisReaderTarget.Close();
                        for (int k = 2; k < count; k++)
                        {
                            string str1 = "INSERT INTO " + TargetTableName[i] + "(" + Target[k - 1] + ") SELECT " + tbl1.Rows[i][k + 1] + " FROM " + OriginalTableName[i]; 
                          SqlCommand command = new SqlCommand(str1, thisConnection);
                          command.ExecuteNonQuery();
                         }
                    
                }
                MessageBox.Show("插入数据成功!");
                Application.Exit();
               

            }
        }





------解决方案--------------------
那说明你的for循环中取数值或者数值原始值就组织错误,好好调试吧