简体   繁体   中英

inserting table values from one table to another

I have two tables in SQL. I need to insert the data from one table to another.I have done it successfully, but the problem is I need to extra add one column value from text box. I will show my code

protected void Button2_Click1(object sender, EventArgs e)
{
    String str1 = "insert into table2(Code,Qty,UPrice,Total) select Code,Qty,UPrice,Total from table1 ;";    
    SqlCommand cmd = new SqlCommand(str1, con);
    con.Open();
    SqlDataAdapter da1 = new SqlDataAdapter();
    cmd.Parameters.AddWithValue("@Num", TextBox1.Text);
    da1.SelectCommand = cmd;
    DataSet ds1 = new DataSet();
    da1.Fill(ds1, "Code");
    GridView1.DataSource = ds1;
    con.Close();
}

Here I need to add Num to my table2 that is not in the table1. So I need to add it from textbox1. How can I add that Num value to the all data from textbox.

I guess Num is your column name, you can modify your query as

insert into table2(Code,Qty,UPrice,Total, Num) 
select Code,Qty,UPrice,Total, textbox1.Text from table1 ;
protected void Button2_Click1(object sender, EventArgs e)
{
String str1 = "insert into table2(Code,Qty,UPrice,Total,Num) select Code,Qty,UPrice,Total,'"+TextBox1.Text+"' from table1 ;";    
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
con.Close();
}

Just set your dynamic value in a temporary variable.

String temp = TextBox1.Text;

Now use this variable with your insert query

String str1 = "insert into table2(Code,Qty,UPrice,Total,Num) 
select Code,Qty,UPrice,Total,'"+temp+"' from table1 ;";    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM