0
我有兩個表table1和table2。我需要將table1中的表值插入到table2中。表1包含列nnum,代碼,qnty和table2也是同一列。我需要插入table1值到table2並根據qnty值重複插入。但我當前的代碼無法正常工作。這裏我附上我需要的格式。圖像中的Table2是我需要得到的東西。根據qnty值重複地將數據從一個表插入到另一個表中
protected void Button15_Click3(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
int j = 0;
connetionString = "Data Source=xxxxx;Initial Catalog=xxxxx;User ID=xxxxx;Password=xxxxxx";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("insert into Table2(Code, Model, Num, Qty) select Code, Model, Num, Qty from Table1", connection);
adapter.Fill(ds);
connection.Close();
String str2 = "select * from Table2;";
SqlCommand xp2 = new SqlCommand(str2, con);
con.Open();
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = xp2;
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Table2");
con.Close();
for (i = 0; i <= Convert.ToInt32(ds2.Tables[0].Rows[i]["Qty"].ToString()) ; i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty) select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
你不得不重新改寫整個事情,因爲現在你將整個表1到表2爲每次迭代取決於數量+ 1 – Thorarins
我沒有得到你,你可以解釋 –
insert into table1(...)select * from table2,將所有行從table2插入到table1中...並且你在for循環中執行qty + 1次 – Thorarins