日期:2014-05-18 浏览次数:21178 次
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(); } }