Sivajihero Hero

Sivajihero Hero

  • NA
  • 105
  • 32.2k

Inserting data from one table to another repeatedly

Jan 13 2016 3:32 AM
I have two tables table1 and table2. I need to insert table values from table1 to table2. The table 1 contain columns nnum,code,qnty and table2 also same column. I need to insert table1 value to table2 and repeat the insertion according to the qnty value.But my current code is not working properly. Here I am attaching the format I need to get. The Table2 in the image is the thing I need to get.
 
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());
}
 
Example:
Table1
Num    Code    Qty
1           A1      3
1           A2      2
1           A3      2
Table2
Num     Code   Qty
1            A1      1
1            A1      1
1           A1       1
1           A2       1
1           A2       1
1           A3        1
1           A3        1
I need to get the output table2 like this
 
 
 

Answers (6)